
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
Power of a Prime Number r in n in C++
In this problem, we are given two integer n and r. Our task is to find the power of the given prime number r in the factorial of the number n.
Let’s take an example to understand the problem
Input − n = 6 r = 2
Output − 4
Explanation −
Factorial n, 6! = 6*5*4*3*2*1 = 720 720 = 24 * 32 * 5, power of 2 is 4
To solve this problem, a simple solution would be directly finding the factorial and then finding the power of the prime number. But this is not the best solution.
Another efficient solution is using a formula,
Power of ‘r’ in n! = floor(n/r) + floor(n/r2) + floor(n/r3) + ...
Example
Program to show the implementation of our solution,
#include <iostream> using namespace std; int primePower(int n, int r) { int count = 0; for (int i = r; (n / i) >= 1; i = i * r) count = count+n/i; return count; } int main() { int n = 6, r = 2; cout<<"Power of prime number "<<r<<"in factorial "<<n<<" is : "<<primePower(n, r); return 0; }
Output
Power of prime number 2in factorial 6 is : 4
Advertisements