Tuesday 7 August 2012

How to obtain prime factors of a positive number in C++

Program to obtain the prime factors of a given number



#include<iostream>

#include<conio.h>

using namespace std;

void prime_factor(int number);

void check_prime(int number, int prime);

int main()
{
       int number = 0;

       cout << "\n\n\t\t __ Prime Factor of Number (Integer or Prime Factorization) __";

       cout << "\n\n\n  Enter the Number  -  ";

       cin >> number;

       prime_factor(number);

       getch();

       return 0;


}

void prime_factor(int number)
{
       int counter = 0, temp = 0, check = 0;

       cout << "\n\n\tPrime Factors of " << number << "  -  ";

       for(counter = 2; counter <= number; counter++)
       {
              check = 0;

              for(temp = 2; temp < counter; temp++)
              {
                     if ((counter % temp) == 0)
                     {
                           check++;
                     }
              }

             
              if (check == 0)
              {
                     check_prime(number, counter);
              }
       }


       cout << "\b\b ";
}

void check_prime(int number, int prime)
{
      
       if ((number % prime) == 0)
       {
                     cout << prime << " , ";
       }
}


Prime Numbers are natural numbers greater than 1 which are either divisible by 1 or itself. Finding out the prime factors of a number is also known as Prime Factorization or Integer Factorization.

In the above scenario first prime numbers from 2 to the number entered are found out and as soon as a prime number is obtained it is passed to a function named check_prime() to check whether the the prime number found can completely divide the number entered through keyboard. If it does the output is printed back to the console.

No comments:

Post a Comment