27 December, 2012

C++ Program To Find Prime Factors Of A Number.

This Post Contains A C++ Program To Find Prime Factors Of A Number With Correct Source Code & Output. This Program Is Written, Compiled & Executed At TurboC/C++3.0 Compiler & Will Help You To Understand The Concept Of 'If...else' & 'While-Loop' From C++ Language. It Is A Well-Structured Program With Proper Comments Which Provides Step-By-Step Description Of Various Features Of The Language In A Simple & Easy-To-Understand Way.

# Note : You Can Simply Copy-Paste The Following Program Or Code Into Compiler For Direct Result.


# Algorithm :

1. Accept any number from user.
2. Initialize i. i=1.
3. Run a loop from 1 to that number to divide the accepted number.
    while( i <= num )
4. if 'i' is a Factor or perfectly divides 'num'.
    if( num % i == 0 )
5. Check whether it is a prime number or not.
    Initialize two variables.
    int j = 1, k = 0;
6. If it is a prime number or k==2.
    Print the Number is a Prime Factor.
7. End if
8. Increment i. i++.
9. End 'while' loop.
10. Stop.


C++ Program To Find Prime Factors Of A Number.

/* Declaration Of Header Files */
# include <iostream.h>
# include <conio.h>

/* Start Of Main Program */
void main()
{

    /* Declaration Of Variables */
    int num,  i;
    clrscr();

    /* Asking For The Input From User */
    cout  <<  " Enter Any Number : ";
    cin >>  num;

    /* Source Code For Computing Prime Factors Of A Number */
    i  =  1;
    while(  i  <=  num  )
    {
        if( num % i == 0 )
        {
            int j = 1, k = 0;
            while( j  <=  i)
            {
                if( i % j == 0 )
                k++;
                j++;
            }
            if( k == 2 )
            cout  <<  i  << " Is A Prime Factor Of "  <<  num;
            cout  <<  "\n";
        }
        i++;
    }
    getch();
}
/* End Of Main Program */

Output :

Enter Any Number :  60

2 Is A Prime Factor Of 60

3 Is A Prime Factor Of 60

5 Is A Prime Factor Of 60



No comments:

Post a Comment

Subscribe To:

Most Commonly Asked Programs In 'C' & 'C++' Language.