prime factor function matlab
11 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
function [z1] = pfact(Z)
if Z>=2
p = 2:Z;
q = mod(Z,p);
a=find(q==0);
z1=p(a)
elseif Z==1
z1 = 1
elseif Z==0
z1 = []
disp("error")
end
I'm trying to get only prime factors but this code gives me all the factors, I need the prime factors that when they multiply with each other they give the original number.
3 comentarios
Respuestas (1)
Dyuman Joshi
el 3 de Abr. de 2023
The code you wrote gives the divisors of Z.
This should work well unless you are dealing with extremely large numbers -
out1=pfact(20)
out2=pfact(prod(primes(15)))
function [z1] = pfact(Z)
if Z>=2
p = primes(sqrt(Z));
z1 = [];
while Z>1
d = p(rem(Z,p)==0);
if isempty(d)
z1=[z1 Z];break
end
z1=[z1 d];
Z = Z/prod(d);
end
z1=sort(z1);
elseif Z==1
z1 = 1;
elseif Z==0
z1 = [];
disp("error")
end
end
0 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!