17. Power of k in factorial of n
β GFG solution to find the highest power of k that divides n! using prime factorization and Legendre's formula. π
The problem can be found at the following link: π Question Link
π§© Problem Description
Given two positive integers n and k, determine the highest value of x such that k^x divides n! (n factorial) completely (i.e., n! % (k^x) == 0).
The task is to find the maximum power of k that can divide n! without leaving a remainder.
π Examples
Example 1
Input: n = 7, k = 2
Output: 4
Explanation: 7! = 5040, and 2^4 = 16 is the highest power of 2 that divides 5040.Example 2
Input: n = 10, k = 9
Output: 2
Explanation: 10! = 3628800, and 9Β² = 81 is the highest power of 9 that divides 3628800.π Constraints
$1 \le n \le 10^5$
$2 \le k \le 10^5$
β
My Approach
The optimal approach uses Prime Factorization combined with Legendre's Formula to efficiently calculate the highest power of k that divides n!:
Prime Factorization + Legendre's Formula
Prime Factorization of k:
Decompose k into its prime factors: k = pβ^aβ Γ pβ^aβ Γ ... Γ pβ^aβ
For each prime factor pα΅’ with exponent aα΅’, we need to find how many times pα΅’ appears in n!
Apply Legendre's Formula:
For each prime p, the highest power of p that divides n! is:
βn/pβ + βn/pΒ²β + βn/pΒ³β + ...This counts how many multiples of p, pΒ², pΒ³, etc. are β€ n
Calculate Maximum Power:
For each prime factor pα΅’ with exponent aα΅’ in k:
Find legendre_count(n, pα΅’) using Legendre's formula
The contribution of this prime is
legendre_count(n, pα΅’) / aα΅’
Find Minimum:
The answer is the minimum of all contributions from prime factors
This ensures k^x divides n! for the maximum possible x
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(βk + Ξ£log_p n), where the sum is over all prime factors p of k. We factorize k in O(βk) time and apply Legendre's formula for each prime factor in O(log_p n) time.
Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space for variables, without storing the prime factors explicitly.
π§βπ» Code (C++)
π§βπ» Code (Java)
π Code (Python)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated