You don't need to go through the whole list. Once you find one prime factor, you factorize your number by that, and continue working with what's left.
For instance, take your example: 600,851,475,143. You can quickly find its first prime factor to be 71. If you divide 600,851,475,143 by 71 you get 8,462,696,833. Both these numbers share the same prime factors except 71. So now you can search the largest factor of the original number but with a search space reduced by 2 orders of magnitude.
Also, notice that your code will fail if the number itself is prime. To fix that, initialize your maximum number as
int largest_prime_factor = 1;
and if it's still 1 in the end, return the number itself. (You could initialize with number, but you'll soon see why I chose 1)
So start by treating 2 as a special case:
long long remain = number; while (remain % 2 == 0) { remain /= 2; largest_prime_factor = 2; }
And then do it similarly inside your loop. Since for prime numbers we only need to check up to its square root, we'll limit our loop by two cases, depending on whether we still think the number could be prime.
- Still prime: test up to sqrt(number)
- No longer prime: test until the maximum factor exceeds what remains.
In the end, your modified code may look like this:
#include <stdio.h> int main() { long long int number=600851475143; long long largest_prime_factor = 1,i,j,k; long long remain = number; while (remain % 2 == 0) { remain /= 2; largest_prime_factor = 2; /* Uncomment to see the factors printf("2 ");*/ } for (i=3; (largest_prime_factor == 1 && i*i <= number) || (largest_prime_factor > 1&& i <= remain); i+=2){ k=0; j=3; for (j=3; j*j<=i;j+=2){ if (i%j==0){ k++; break; } } if (k==0 && remain%i==0) { largest_prime_factor=i; while (remain % i == 0) { /* Uncomment to see the factors printf("%d ", i); */ remain /= i; } } } printf("The largest prime factor of %Ld is: %Ld", number, largest_prime_factor); return 0; }
Also notice that other variables should also be of type (long long).
The bottleneck will be checking if each number is prime, and the whole process will still be slow if the prime factors themselves are large. But you can get a much faster average case. For your example, this algorithm gets the factors 71, 839, 1471, and 6857 in less than a second.
largest_prime_factorandisurely cannot be a plainint, as they have to keep numbers of the same magnitude ofnumber.