Wednesday, June 23, 2021
Home coding Write a program to print the prime factor of given number.

Write a program to print the prime factor of given number.

Given a number we have to calculate the prime factor of number and print the resultant value .

So what is prime factor of number?

prime factor of a number is a factor that is prime number.

Example:

input:30
output:2 3 5

Logic:

step 1- if n is divisble by 2 ,divide them till n is not divisble by 2.
step 2-here n is odd.then divide number n by i.
step 3-here you get all prime factor of number n.

Code-

#include <bits/stdc++.h> 
using namespace std; 
int main() 
{ 
int n;
cin>>n;
while (n % 2 == 0) 
{ 
		cout<<2<< " "; 
		n=n/2; 
    
} 
for (int i = 3;i <=sqrt(n);i=i + 2) 
{ 
	while (n % i == 0) 
	{ 
			cout<<i<<" "; 
			n = n/i; 
    } 
} 
	if (n>2) 
	{
		cout<<n<<" "; 
	}
} 

Output:

30

2 3 5

Time complexity:0(N)

Space Complexity:O(1)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments