Loop is taking a lot of time

1 次查看(过去 30 天)
Hello,
I am trying to create a code that gives me the prime factors of a number but it is requiring a lot of time. Here is my code:
N = 12345678;
t=1;
for j = 2 : N
s = 0;
while N/j == floor(N/j)
N = N/j;
s = s + 1;
end
if s > 0
for k=1:s
primefactors(t)=j;
t=t+1;
end
end
end
disp(primefactors)
Now, I understand that loops can take time if the number is large, although I've noticed that when you take off the ; after "primefactors(t)=j;", the output displays all of the prime numbers and just stops. I've also tried to add this code to various places to try and force the program to stop once it has found all of the prime numbers:
if prod(primefactors)==N
break
end
Unfortunately, the outcome is the same. Is there a reason why this isn't working, or is there another work around aside from rewriting the code?
Thanks in advance!
edit: I am also using octave if that makes any difference.

采纳的回答

David Sanchez
David Sanchez 2013-5-27
Matlab 2013 in a i3 machine takes time =
0.3825
seconds to perform your code. I guess your problem lies on your machine.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by