# Print all prime factors and their powers in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

In this problem, we are given a number N, and we have to find all unique prime factors and their powers that divide the number.

Let’s take an example to understand the topic −

Input: 55
Output:
5 power 1
11 power 1

Explanation −

55 is divisible by 5 and 11.

To solve this problem, an easy approach to solving the problem is to find prime factors of N. And then find power of the prime number that divides the number N and print it.

## Algorithm

Efficient Approach

Step 1: Find an array s[N+1].
s[i] = prime factor of i dividing N.
Step 2: Find all powers of i. prime = s[N] and pow = 1.
Step 3: While (N > 1) :
Step 3.1: N /= s[N];
Step 3.2: if(prime = s[N]) : pow++
Step 4: print prime and pow.

## Example

Live Demo

#include<bits/stdc++.h>
using namespace std;
void primes(int N, int s[]){
vector <bool> prime(N+1, false);
for (int i=2; i<=N; i+=2)
s[i] = 2;
for (int i=3; i<=N; i+=2){
if (prime[i] == false){
s[i] = i;
for (int j=i; j*i<=N; j+=2){
if (prime[i*j] == false){
prime[i*j] = true;
s[i*j] = i;
}
}
}
}
}
void generatePrimeFactors(int N) {
int s[N+1];
primes(N, s);
cout<<"Factor\tPower"<<endl;
int prime = s[N];
int power = 1;
while (N > 1){
N /= s[N];
if (prime == s[N]){
power++;
continue;
}
cout<<prime<<"\t"<<power<<endl;
prime = s[N];
power = 1;
}
}
int main() {
int N = 55;
cout<<"The prime factors are and their powers are :\n";
generatePrimeFactors(N);
return 0;
}

## Output

The prime factors are and their powers are −

Factor Power
5 1
11 1
Updated on 17-Jan-2020 11:16:29