Search code examples
cprime-factoring

C-program for finding prime factors, compilation is not stopping


My Program to calculate the largest prime factor of 600851475143, is stuck and never stops during compilation and execution. Does anyone know why it does not finish execution?

#include <stdio.h> //Edited the #includes(typo) to #include 
 int main (void)
{

    long long int num = 600851475143 ;
    long long int factorCount;
    long long int bigFactor;

    for ( long long int i=1 ; i <= num; i+=2 )// Iterating through all numbers from 2, smaller than or equal to num
    {
        if ( num % i == 0) // If the number "i" is a factor of num i.e. If "i" perfectly divides num
        {
            factorCount = 0;
            //checking whether a factor "i" , is a prime factor of num
            for ( long long int j=2; j <= i ; j++  ) // Iterating through all numbers from 2, smaller than or equal to "i"
            {
                if ( i % j == 0) // If the number "j" prefectly divides or is a factor of "i"
                {
                    factorCount++; //Add 1 to factorCount
                };
            };

            if ( factorCount == 1 ) // If factorCount has not exceeded 1 i.e., the number "i" is a prime number
            {
                bigFactor = i;
            };
        };

    };
    printf("The largets prime factor of %lli is %lli\n",num,bigFactor );

    return 0;
}

Solution

  • I am not sure whether I understood your question .. so you just want to get the biggest prime factor for a certain number? If this is the case, then just do the following:

    #include <stdio.h>
    
    #define NUMBER 600851475143
    
    int main (void)
    {
        long long int num = NUMBER;
        long long int factor;
    
        for (factor=2 ; num != 1; factor++) {
            if (num % factor == 0) {
                num = num / factor;
                factor = factor-1;
            }
        }
        printf("The largets prime factor of %lli is %lli\n",NUMBER, factor);
        return 0;
    }
    

    Why this works: the first prime factor you find is the smallest prime factor of the number; the last prime factor is the biggest. Therefore once you have found a prime factor p, there does not exist a prime factor smaller than p, because otherwise you would have found that smaller prime factor before. Hence your next prime factor is greater equals p.