Friday, 15 September 2017

Prime Factors of a number using c/c++

This code prints all prime factors of a specified number in both multiplication and power form. There are two separate functions to print in different forms. 

The explanation of code is given in the code in comments. The code may be improved for large integers and performance.

Source Code:

#include <stdio.h>
#include <iostream>

using namespace std;

/* A function to print all prime factors in multiplication form of a given number */

void PrimeFactorsInMultiplication(int number)
{
      if (number < 1)
            return;
      //print the input
      cout << number << " = ";
      // Print the number of 2s that divide number
      while (number % 2 == 0)
      {
            if (number == 2)
                  cout << "2 ";
            else
                  cout << "2 x ";
            number = number / 2;
      }
      // number must be odd. So we can skip
      // one element (Note i = i +2)
      for (int i = 3; i*i <= number; i = i + 2)
      {
            // While i divides n, print i and divide n
            while (number%i == 0)
            {
                  if (number == i)
                        cout << i;
                  else
                        cout << i << " x ";
                  number = number / i;
            }
      }

      // the condition is to handle the case when number is a prime number greater than 2
      if (number > 2)
            cout << number;
}

/* A function to print all prime factors in power form of a given number*/

void PrimeFactorInPower(int number)
{
      int __se, count = 0;
      //print the input
      cout << number << " = ";
      for (__se = 2; __se <= number; __se++)
      {
            //calc the power of primes using a counter
            while ((number%__se) == 0)
            {
                  number = number / __se;
                  count++;
            }
            //if count >=1 then print the prime with their power
            if (count != 0)
            {
                  cout << __se << "^" << count << "\t";
                  count = 0;
            }
      }
}

/* main function to test above functions */
int main()
{
      cout << "Prime Facotrs in multiplication form:\n\n";
      for (size_t i = 1000; i < 1010; i++)
      {
            PrimeFactorsInMultiplication(i);
            cout << "\n";
      }
      cout << "\n\nPrime Facotrs in power form:\n\n";
      for (size_t i = 1000; i < 1010; i++)
      {
            PrimeFactorInPower(i);
            cout << "\n";
      }
      getchar();
      return 0;
}

Output: