find prime factors of a whole number in matlab

Below is the implementation of finding prime factors of a whole number using MATLAB:

main.m
% Taking an input number whose prime factors needs to be found
number = input('Enter a number to find its prime factors: ');

% Initializing an empty array to store prime factors
prime_factors = [];

% Finding prime factors of the given number
for i = 2:number
    while (mod(number,i) == 0)
        prime_factors(end+1) = i;
        number = number/i;
    end
end

% Displaying the prime factors
fprintf('Prime factors of the given number are: ');
disp(prime_factors);
470 chars
18 lines

In this implementation, we are taking an input number from the user and initializing an empty array to store prime factors. We then loop over all numbers from 2 to the given number and keep dividing the input number by the current number until it is not divisible anymore. If the current number is a factor of the input number, we store it in the prime factors array. Finally we display the prime factors of the input number.

gistlibby LogSnag