Write a C++ Program to Find Prime Factors of a Number with an example. In this prime factors example, we used nested while loop.
#include<iostream>
using namespace std;
int main()
{
int number, i = 1, j, count;
cout << "\nPlease Enter the Number to find the Prime Factors = ";
cin >> number;
while (i <= number)
{
count = 0;
if(number % i == 0)
{
j = 1;
while(j <= i)
{
if(i % j == 0)
{
count++;
}
j++;
}
if(count == 2)
{
cout << i << " is a Prime Factor\n";
}
}
i++;
}
return 0;
}

The below shown Program will Find the Prime Factors of a Number using For Loop.
#include<iostream>
using namespace std;
int main()
{
int number, i, j, count;
cout << "\nPlease Enter the Number to find the Prime Factors = ";
cin >> number;
for(i = 1; i <= number; i++)
{
count = 0;
if(number % i == 0)
{
for(j = 1; j <= i; j++)
{
if(i % j == 0)
{
count++;
}
}
if(count == 2)
{
cout << i << " is a Prime Factor\n";
}
}
}
return 0;
}
Please Enter the Number to find the Prime Factors = 72
2 is a Prime Factor
3 is a Prime Factor
It is another example to find the prime factors of a given number.
#include<iostream>
using namespace std;
int main()
{
int number, i, j, isPrime, x;
cout << "\nPlease Enter the Number to find the Prime Factors = ";
cin >> number;
for (i = 2; i <= number; i++)
{
if(number % i == 0)
{
isPrime = 1;
for (j = 2; j <= i/2; j++)
{
x = i % j;
if(i % j == 0)
{
isPrime = 0;
break;
}
}
if(isPrime == 1)
{
cout << i << " is a Prime Factor\n";
}
}
}
return 0;
}
Please Enter the Number to find the Prime Factors = 120
2 is a Prime Factor
3 is a Prime Factor
5 is a Prime Factor
C++ Program to Find Prime Factors of a Number using recursion
In this example, the void findFactors(int number) method finds the factors of a given number. And, void findPrime(int number) methods find the prime numbers.
#include<iostream>
using namespace std;
void findPrime(int number)
{
int i, count = 0;
for (i = 2; i <= number/2; i++)
{
if(number % i == 0)
{
count++;
}
}
if(count == 0 && number != 1 )
{
cout << number << " is a Prime Factor\n";
}
}
void findFactors(int number)
{
for (int i = 1; i <= number; i++)
{
if(number % i == 0)
{
findPrime(i);
}
}
}
int main()
{
int number;
cout << "\nPlease Enter the Number to find the Prime Factors = ";
cin >> number;
cout << "\nThe Prime Factors of a Given Number " << number << " are\n";
findFactors(number);
return 0;
}
Please Enter the Number to find the Prime Factors = 266
The Prime Factors of a Given Number 266 are
2 is a Prime Factor
7 is a Prime Factor
19 is a Prime Factor