Domanda

i wanted to find largest prime factor of 600851475143, and i wrote a code that can calculate prime factor of 13195 or less numbers. but my code cannot calculate 600851475143 this numbers largest prime factor why is that ?
here is my code:

#include <stdio.h>
#include <math.h>

int main( ){

    int n, a, b;
    printf( "enter a number=> " );
    scanf( "%d", &n );
    for ( a = n; a >= 2; a-- ){
        for ( b = 2; b <= a; b++ ){
            if ( a % b == 0 ){break;}
            else if ( b == a - 1 ){
             if( n % a == 0 ){
             printf("here is the largest prime number => %d\n", a);
                return 0;
                }
            }
        }
    }
    return 0;
}
È stato utile?

Soluzione

Here 600851475143 is too big to hold for int data type. Use long long instead of int.So,change the following lines in your code to this:

long long n, a, b;

scanf( "%lld", &n );

printf("here is the largest prime number => %lld\n", a);

Checkout the link for details : Range of values in C Int and Long 32 - 64 bits

Altri suggerimenti

That value is larger than the maximum value of the int data type. You will likely need a 64 bit INT value.

Are types like uint32, int32, uint64, int64 defined in any stdlib header?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top