How to find the largest prime factor of 600851475143?

前端 未结 5 1076
挽巷
挽巷 2021-01-16 19:08
#include 
main()
{
    long n=600851475143;
    int i,j,flag;
    for(i=2;i<=n/2;i++)
    {
        flag=1;
        if(n%i==0)//finds factors backw         


        
5条回答
  •  迷失自我
    2021-01-16 19:59

    Use longs in place of ints. Better still, use uint64_t which has been defined since C99 (acknowledge Zaibis). It is a 64 bit unsigned integral type on all platforms. (The code as you have it will overflow on some platforms).

    And now we need to get your algorithm working more quickly:

    Your test for prime is inefficient; you don't need to iterate over all the even numbers. Just iterate over primes; up to and equal to the square root of the number you're testing (not half way which you currently do).

    Where do you get the primes from? Well, call your function recursively. Although in reality I'd be tempted to cache the primes up to, say, 65536.

提交回复
热议问题