Prime Factor in C++ Program


Prime Factor is a prime number which is the factor of the given number.

Factor of a number are the numbers that are multiplied to get the given number.

Prime Factorisation is the process of recursively dividing the number with its prime factors to find all the prime factors of the number.

Example :
N = 120
Prime factors = 2 5 3
Factorization : 2 * 2 * 2 * 3 * 5

Some points to remember about prime factors of a number

  • Set of prime factors of a number is unique.
  • Factorization is important in many mathematical calculations like divisibility, finding common denominators, etc.
  • It’s an important concept in cryptography.

Program to find prime factors of a number

Example

 Live Demo

#include <iostream>
#include <math.h>
using namespace std;
void printPrimeFactors(int n) {
   while (n%2 == 0){
      cout<<"2\t";
      n = n/2;
   }
   for (int i = 3; i <= sqrt(n); i = i+2){
      while (n%i == 0){
         cout<<i<<"\t";
         n = n/i;
      }
   }
   if (n > 2)
   cout<<n<<"\t";
}
int main() {
   int n = 2632;
   cout<<"Prime factors of "<<n<<" are :\t";
   printPrimeFactors(n);
   return 0;
}

Output

Prime factors of 2632 are :2   2   2   7   47

Updated on: 03-Feb-2020

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements