Software & Finance





C Programming (Turbo C++ Compiler) - Getting Prime Factors of a Number





Given a number, we can find out what would be the prime factors of  the number. But it is not easy to find out since we have to go through couple of iteratons.

Prime Factor For 9360 = 13 *  5 *  3 *  3 *  2 *  2 *  2 *  2

Note that all the numbers 13, 5, 3, 2 are prime numbers.


Source Code


#include <stdio.h>

 

 

#define MAX_SIZE 15000

 

enum bool

{

      false = 0, true = 1

};

 

bool IsPrimeNumber(long num)

{

    bool bPrime = true;

    long factor = num / 2;

    long i = 0;

 

    for(i = 2; i <= factor; i++)

    {

      if( (num % i) == 0)

          bPrime = false;

    }

    return bPrime;

}

 

long GetPrimeFactors(long num, long *arrResult)

{

    long count = 0;

    long arr[MAX_SIZE];

 

    long i = 0;

 

    long idx = 0;

 

    for(i = 2; i <= num; i++)

    {

      if(IsPrimeNumber(i) == true)

          arr[count++] = i;

    }

 

    while(1)

    {

      if(IsPrimeNumber(num) == true)

      {

          arrResult[idx++] = num;

          break;

      }

      for(i = count - 1; i >= 0; i--)

      {

          if( (num % arr[i]) == 0)

          {

            arrResult[idx++] = arr[i];

            num = num / arr[i];

            break;

          }

      }

    }

    return idx;

}

 

long main()

{

    long num1;

    long result[MAX_SIZE];

 

    long count =  0;

    int i = 0;

 

 

    printf("Enter a Number: ");

    scanf("%d", &num1);

 

    count = GetPrimeFactors(num1, result);

 

    printf("Prime Factor For %d = ", num1);

 

 

    for(i = 0; i < count; i++)

    {

      printf("%d", result[i]);

      if(i != count - 1)

            printf(" * ");

    }

    printf("\n");

 

    return 0;

}

Output


Enter a Number: 9360

Prime Factors For 9360 = 13 *  5 *  3 *  3 *  2 *  2 *  2 *  2

Press any key to continue . . .

 

Enter a Number: 48125

Prime Factors For 48125 = 11 *  7 *  5 *  5 *  5 *  5

Press any key to continue . . .