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)