In Matlab, write a function that takes a relatively small (less than 100 billion) positive integer input and outputs the prime factorization of that integer using as few built-in functions as possible. Explain the processes with comments.
NOTE: Do not use the functions factor(n), primes(n), or isprime(n). You should be able to write out what these functions do yourself if you want to be able to do something similar.
MATLAB Script (Run it as a script, NOT from command window):
close all
clear
clc
% maximum value of n = 100 billion
n = 1234567890;
factors = find_factors(n);
fprintf('Factors of %d:\n', n)
disp(factors(:))
function factors = find_factors(n)
factors = [];
for i = 2:floor(sqrt(n))
if prime(i)
if rem(n, i) == 0
factors = [factors i];
end
end
end
end
function prime_stat = prime(n)
prime_stat = true;
count = 0;
for i = 1:n
if mod(n,i) == 0
count = count + 1;
end
end
if count > 2
prime_stat = false;
end
end
Example Output:
Factors of 1234567890:
2
3
5
3607
3803
Get Answers For Free
Most questions answered within 1 hours.