
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- Finding the power of prime number p in n! in C++
- Primitive root of a prime number n modulo n in C++
- Find power of power under mod of a prime in C++
- Kth prime number greater than N in C++
- Program for power of a complex number in O(log n) in C++
- Number of digits in 2 raised to power n in C++
- How to find prime factors of a number in R?
- Prime factors of a big number in C++
- Nearest prime less than given number n C++
- How to find the fractional power of a negative number in R?
- Count pairs with sum as a prime number and less than n in C++
- Mersenne Prime Number in C++.
- Find power of a number using recursion in C#
- Check if a number is a power of another number in C++
- Queries to check if a number lies in N ranges of L-R in C++

Advertisements