How to find the largest prime factor of 600851475143?

前端 未结 5 1074
挽巷
挽巷 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:35

    From ISO/IEC 9899:TC3

    5.2.4.2.1 Sizes of integer types

    [...]

    Their implementation-defined values shall be equal or greater in magnitude(absolute value) to those shown, with the same sign.

    [...]

    — minimum value for an object of type long int

    LONG_MIN -2147483647 // -(2^31 - 1)

    — maximum value for an object of type long int

    LONG_MAX +2147483647 // 2^31 - 1

    EDIT:

    Sorry I forgot to add what this should tell you.

    The point is long doesn't even need to be able to hold the value you mentioned, as the standard says it has to be able to hold at least 4 Bytes with sign so it could be possible that your machine is just able to hold values up to 2147483647 in a variable of type long.

    0 讨论(0)
  • 2021-01-16 19:53

    Try changing n to long long int .. and change i,j to long

    EDIT: define n like this :

    long long int n = 600851475143LL;
    

    LL - is a suffix to enforce long long type ...

    0 讨论(0)
  • 2021-01-16 19:57

    One potential problem is that i and j are int, and could overflow for large n (assuming int is narrower than long, which it often is).

    Another issue is that for n=600,851,475,143 your program does quite a lot of work (the largest factor is 6857). It is not unreasonable to expect it to take a long time to complete.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-16 20:00

    On 32-bit machine long range from -2,147,483,648 to 2,147,483,647 and On 64-bit machine its range is from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (NOTE: This is not mandated by C standard and may vary from one compiler to another).
    As OP said in comment he is on 32-bit, 600851475143 goes out of range as it is not fit in the range of long.

    0 讨论(0)
提交回复
热议问题