Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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
Finding the power of prime number p in n! in C++
In this problem, we are given a number n and a prime number p. Our task is to find the power of prime number p in n!
Let's take an example to understand the problem,
Input : n = 6, p = 2 Output : 4
Solution Approach
A simple solution to the problem is by simply finding the values of n!. And the factorize it, and find the power of prime number p in the factorization.
Here, the number can be represented as the power factorization of 2 in 5! = 30 is 3.
The value of n factorial is
$$n!\:=\:n^*(n-1)^*(n-2)^*(n-3)\dotso{^*}2^*1$$
$$n!\:=\:3^*2^*1\:=\:6$$
Let take n = 6 and p = 2,
n! = 6! = (2*3*4*5*6)
n! = 720
Factorisation of 720 is 2*2*2*2*3*3*5
The power of 2 in the factorisation of 6! is 4.
Hence the output is 4.
Example
Program to illustrate the working of our solution
#include <iostream>
using namespace std;
int powerOfPrimeNfactorial(int N, int P){
int primePower = 0;
int factVal = P;
while (factVal <= N) {
primePower += N / factVal;
factVal = factVal * P;
}
return primePower;
}
int main(){
int N = 6;
int P = 2;
cout<<"The power of prime number "<<P<<" in "<<N<<"! is "<<powerOfPrimeNfactorial(N, P) << endl;
return 0;
}
Output
The power of prime number 2 in 6! is 4
Advertisements