MATLAB: Can someone help with the code? (about factores primes)

codeMATLABprojecteuler

Hi, i'm beginner in this language
It seems be simple. What is the largest prime factor of the number 600851475143 ?
i try that, what is wrong?
n=600861475143
prime=2
while n~=1
prime=prime+1
if mod(n,prime)==0
n=n/prime
end
end

Best Answer

Trivial.
factor(600861475143)
ans =
3 3 3 3 60943 121721
max(factor(600861475143))
ans =
121721
Ok, I suppose you are not allowed to use factor. But, perhaps you need to look at the actual factors of that number, and think about why your code failed.
What happens when there are repeated factors? You will find the first factor of 3 there, but then you increment prime. So you never found those second, third, or fourth factors of 3. At the very least, once you find a prime factor, you need to see if it is a multiple factor of your number.
As bad, what would have happened with your code had your teacher given you this number instead: 600861475147
This last number is prime. How many iterations of your loop would be needed to identify that it is indeed prime? 600 BILLION iterations of that loop (essentially 600 billion trial divides) would be needed before it would give up. (A modulus computation is essentially equivalent to a division.)
The point is, do you need to test for a factor that is larger than sqrt(n)? Think about it. For any number n, how many prime factors can the number n have that are larger than sqrt(n)?