Featured
- Get link
- X
- Other Apps
C++ Program to print prime factors
// Program to print all prime factors of a given number
# include <iostream.h>
# include <math.h>
// A function to print all prime factors of a given number n
void primeFactors(int n)
{
// Print the number of 2s that divide n
while (n%2 == 0)
{
cout<<"2*";
n = n/2;
}
// n must be odd at this point. So we can skip one element (Note i = i +2)
for (int i = 3; i <= sqrt(n); i = i+2)
{
// While i divides n, print i and divide n
while (n%i == 0)
{
cout<<i<<"*";
n = n/i;
}
}
// This condition is to handle the case whien n is a prime number
// greater than 2
if (n > 2)
cout<<n<<"*";
}
void main()
{
int n;
cout<<"\nEnter A Number\n";
cin>>n;
primeFactors(n);
cout<<"\b";
}
OUTPUT:
# include <iostream.h>
# include <math.h>
// A function to print all prime factors of a given number n
void primeFactors(int n)
{
// Print the number of 2s that divide n
while (n%2 == 0)
{
cout<<"2*";
n = n/2;
}
// n must be odd at this point. So we can skip one element (Note i = i +2)
for (int i = 3; i <= sqrt(n); i = i+2)
{
// While i divides n, print i and divide n
while (n%i == 0)
{
cout<<i<<"*";
n = n/i;
}
}
// This condition is to handle the case whien n is a prime number
// greater than 2
if (n > 2)
cout<<n<<"*";
}
void main()
{
int n;
cout<<"\nEnter A Number\n";
cin>>n;
primeFactors(n);
cout<<"\b";
}
OUTPUT:
- Get link
- X
- Other Apps
Labels:
C++ Program to print prime factors
prime factors program in C++
program to print prime factors of a given number in c++
Popular Posts
C++ program to display numbers which get reversed after multiplying by 4
- Get link
- X
- Other Apps
Comments
Post a Comment