Prime Factorization Function Script

4 次查看(过去 30 天)
Write function script that accepts a value which should be prime factorized. The function script should output the respective factors of the input value.
Could someone help me with what this would look like in terms of code using loops/conditional statements?

回答(1 个)

David Hill
David Hill 2020-4-26
function pfactors=pfactor(x)
pfactors=[];
for k=primes(x)
while mod(x,k)==0
pfactors=[pfactors,k];
x=x/k;
end
end
end
  2 个评论
Anthony Bartsch
Anthony Bartsch 2020-4-26
Thank you! Could you rewrite your code without using primes() command by any chance?
David Hill
David Hill 2020-4-26
function pfactors=pfactor(x)
pfactors=[];
for k=2:x
while mod(x,k)==0
pfactors=[pfactors,k];
x=x/k;
end
end
end

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Performance and Memory 的更多信息

产品


版本

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by