 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print all prime factors and their powers in C++
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
#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
Advertisements
 