Power of a prime number ‘r’ in n!
Given an integer n, find the power of a given prime number(r) in n!
Input : n = 6 r = 3 Factorial of 6 is 720 = 2^4 * 3^2 *5 (prime factor 2,3,5) and power of 3 is 2 Output : 2 Input : n = 2000 r = 7 Output : 330
A simple method is to first calculate factorial of n, then factorize it to find the power of a prime number.
The above method can cause overflow for a slightly bigger numbers as factorial of a number is a big number. The idea is to consider prime factors of a factorial n.
Legendre Factorization of n!
For any prime number p and any integer n, let Vp(n) be the exponent of the largest power of p that divides n (that is, the p-adic valuation of n). Then
Vp(n) = summation of floor(n / p^i) and i goes from 1 to infinity
While the formula on the right side is an infinite sum, for any particular values of n and p it has only finitely many nonzero terms: for every i large enough that p^i > n, one has floor(n/p^i) = 0 . since, the sum is convergent.
Power of ‘r’ in n! = floor(n/r) + floor(n/r^2) + floor(n/r^3) + ....
Program to count power of a no. r in n! based on above formula.
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.