Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Largest power of k in n! (factorial) where k may not be prime

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Given two numbers k and n, find the largest power of k that divides n!  
Constraints:  K > 1

Examples: 

Input : n = 7, k = 2
Output : 4
Explanation : 7! = 5040
The largest power of 2 that
divides 5040 is 24.

Input : n = 10, k = 9
Output :  2
The largest power of 9 that
divides 10! is 92.

We have discussed a solution in below post when k is always prime.
Legendre’s formula (Given p and n, find the largest x such that p^x divides n!)
Now to find the power of any non-prime number k in n!, we first find all the prime factors of the number k along with the count of number of their occurrences. Then for each prime factor, we count occurrences using Legendre’s formula which states that the largest possible power of a prime number p in n is ⌊n/p⌋ + ⌊n/(p2)⌋ + ⌊n/(p3)⌋ + ……
Over all the prime factors p of K, the one with the minimum value of findPowerOfK(n, p)/count will be our answer where count is number of occurrences of p in k.
 

C++




// CPP program to find the largest power
// of k that divides n!
#include <bits/stdc++.h>
using namespace std;
 
// To find the power of a prime p in
// factorial N
int findPowerOfP(int n, int p)
{
    int count = 0;
    int r=p;
    while (r <= n) {
 
        // calculating floor(n/r)
        // and adding to the count
        count += (n / r);
 
        // increasing the power of p
        // from 1 to 2 to 3 and so on
        r = r * p;
    }
    return count;
}
 
// returns all the prime factors of k
vector<pair<int, int> > primeFactorsofK(int k)
{
    // vector to store all the prime factors
    // along with their number of occurrence
    // in factorization of k
    vector<pair<int, int> > ans;
 
    for (int i = 2; k != 1; i++) {
        if (k % i == 0) {
            int count = 0;
            while (k % i == 0) {
                k = k / i;
                count++;
            }
 
            ans.push_back(make_pair(i, count));
        }
    }
    return ans;
}
 
// Returns largest power of k that
// divides n!
int largestPowerOfK(int n, int k)
{
    vector<pair<int, int> > vec;
    vec = primeFactorsofK(k);
    int ans = INT_MAX;
    for (int i = 0; i < vec.size(); i++)
 
        // calculating minimum power of all
        // the prime factors of k
        ans = min(ans, findPowerOfP(n,
              vec[i].first) / vec[i].second);
 
    return ans;
}
 
// Driver code
int main()
{
    cout << largestPowerOfK(7, 2) << endl;
    cout << largestPowerOfK(10, 9) << endl;
    return 0;
}


Java




// JAVA program to find the largest power
// of k that divides n!
import java.util.*;
 
class GFG
{
     
static class pair
{
    int first, second;
    public pair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }
}
// To find the power of a prime p in
// factorial N
static int findPowerOfP(int n, int p)
{
    int count = 0;
    int r = p;
    while (r <= n)
    {
 
        // calculating Math.floor(n/r)
        // and adding to the count
        count += (n / r);
 
        // increasing the power of p
        // from 1 to 2 to 3 and so on
        r = r * p;
    }
    return count;
}
 
// returns all the prime factors of k
static Vector<pair > primeFactorsofK(int k)
{
    // vector to store all the prime factors
    // along with their number of occurrence
    // in factorization of k
    Vector<pair> ans = new Vector<pair>();
 
    for (int i = 2; k != 1; i++)
    {
        if (k % i == 0)
        {
            int count = 0;
            while (k % i == 0)
            {
                k = k / i;
                count++;
            }
 
            ans.add(new pair(i, count));
        }
    }
    return ans;
}
 
// Returns largest power of k that
// divides n!
static int largestPowerOfK(int n, int k)
{
    Vector<pair > vec = new Vector<pair>();
    vec = primeFactorsofK(k);
    int ans = Integer.MAX_VALUE;
    for (int i = 0; i < vec.size(); i++)
 
        // calculating minimum power of all
        // the prime factors of k
        ans = Math.min(ans, findPowerOfP(n,
            vec.get(i).first) / vec.get(i).second);
 
    return ans;
}
 
// Driver code
public static void main(String[] args)
{
    System.out.print(largestPowerOfK(7, 2) +"\n");
    System.out.print(largestPowerOfK(10, 9) +"\n");
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python3 program to find the largest power
# of k that divides n!
import sys
 
# To find the power of a prime p in
# factorial N
def findPowerOfP(n, p) :
 
    count = 0
    r = p
    while (r <= n) :
 
        # calculating floor(n/r)
        # and adding to the count
        count += (n // r)
 
        # increasing the power of p
        # from 1 to 2 to 3 and so on
        r = r * p
      
    return count
 
# returns all the prime factors of k
def primeFactorsofK(k) :
 
    # vector to store all the prime factors
    # along with their number of occurrence
    # in factorization of k
    ans = []
    i = 2
    while k != 1 :
        if k % i == 0 :
            count = 0
            while k % i == 0 :
                k = k // i
                count += 1
            ans.append([i , count])
        i += 1
 
    return ans
 
# Returns largest power of k that
# divides n!
def largestPowerOfK(n, k) :
 
    vec = primeFactorsofK(k)
    ans = sys.maxsize
    for i in range(len(vec)) :
 
        # calculating minimum power of all
        # the prime factors of k
        ans = min(ans, findPowerOfP(n, vec[i][0]) // vec[i][1])
 
    return ans
 
print(largestPowerOfK(7, 2))
print(largestPowerOfK(10, 9))
 
# This code is contributed by divyesh072019


C#




// C# program to find the largest power
// of k that divides n!
using System;
using System.Collections.Generic;
 
class GFG
{
     
class pair
{
    public int first, second;
    public pair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }
}
 
// To find the power of a prime p in
// factorial N
static int findPowerOfP(int n, int p)
{
    int count = 0;
    int r = p;
    while (r <= n)
    {
 
        // calculating Math.Floor(n/r)
        // and adding to the count
        count += (n / r);
 
        // increasing the power of p
        // from 1 to 2 to 3 and so on
        r = r * p;
    }
    return count;
}
 
// returns all the prime factors of k
static List<pair > primeFactorsofK(int k)
{
    // vector to store all the prime factors
    // along with their number of occurrence
    // in factorization of k
    List<pair> ans = new List<pair>();
 
    for (int i = 2; k != 1; i++)
    {
        if (k % i == 0)
        {
            int count = 0;
            while (k % i == 0)
            {
                k = k / i;
                count++;
            }
 
            ans.Add(new pair(i, count));
        }
    }
    return ans;
}
 
// Returns largest power of k that
// divides n!
static int largestPowerOfK(int n, int k)
{
    List<pair > vec = new List<pair>();
    vec = primeFactorsofK(k);
    int ans = int.MaxValue;
    for (int i = 0; i < vec.Count; i++)
 
        // calculating minimum power of all
        // the prime factors of k
        ans = Math.Min(ans, findPowerOfP(n,
            vec[i].first) / vec[i].second);
 
    return ans;
}
 
// Driver code
public static void Main(String[] args)
{
    Console.Write(largestPowerOfK(7, 2) +"\n");
    Console.Write(largestPowerOfK(10, 9) +"\n");
}
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
 
// JavaScript program to find the largest power
// of k that divides n!
 
class pair
{
    constructor(first,second)
    {
        this.first = first;
        this.second = second;
    }
}
 
// To find the power of a prime p in
// factorial N
function findPowerOfP(n,p)
{
    let count = 0;
    let r = p;
    while (r <= n)
    {
  
        // calculating Math.floor(n/r)
        // and adding to the count
        count += Math.floor(n / r);
  
        // increasing the power of p
        // from 1 to 2 to 3 and so on
        r = r * p;
    }
    return count;
}
 
// returns all the prime factors of k
function primeFactorsofK(k)
{
    // vector to store all the prime factors
    // along with their number of occurrence
    // in factorization of k
    let ans = [];
  
    for (let i = 2; k != 1; i++)
    {
        if (k % i == 0)
        {
            let count = 0;
            while (k % i == 0)
            {
                k = Math.floor(k / i);
                count++;
            }
  
            ans.push(new pair(i, count));
        }
    }
    return ans;
}
 
// Returns largest power of k that
// divides n!
function largestPowerOfK(n,k)
{
    let vec = [];
    vec = primeFactorsofK(k);
    let ans = Number.MAX_VALUE;
    for (let i = 0; i < vec.length; i++)
  
        // calculating minimum power of all
        // the prime factors of k
        ans = Math.min(ans, findPowerOfP(n,
            vec[i].first) / vec[i].second);
  
    return ans;
}
 
// Driver code
document.write(largestPowerOfK(7, 2) +"<br>");
document.write(largestPowerOfK(10, 9) +"<br>");
 
 
// This code is contributed by rag2127
 
</script>


Output

4
2

Time Complexity: O(k*log(n))
Auxiliary Space: O(k)
This article is contributed by ShivamKD. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
 

Approach 2: –Another approach to find the largest power of a non-prime number k in n! is by using the concept of the number of times a factor appears in a number’s prime factorization. The number of times a factor p appears in n! is given by the sum of the quotients n/p, n/p^2, n/p^3, and so on until the quotient becomes 0.

We can extend this concept to find the largest power of k in n! by considering the prime factorization of k. If k can be written as a product of primes, say k = p1^a1 * p2^a2 * … * pk^ak, then the largest power of k in n! is given by the minimum of the largest powers of each prime pi in k.

C++




#include <bits/stdc++.h>
using namespace std;
 
int largestPower(int n, int k) {
    // find prime factorization of k and their respective exponents
    map<int, int> factors;
    for(int i=2; i*i<=k; i++) {
        while(k % i == 0) {
            factors[i]++;
            k /= i;
        }
    }
    if(k > 1) factors[k]++;
     
    int minPower = INT_MAX;
    // find the largest power of each prime factor and take their minimum
    for(auto it : factors) {
        int p = it.first, a = it.second;
        int power = 0;
        for(long long i=p; i<=n; i*=p) {
            power += n/i;
        }
        minPower = min(minPower, power/a);
    }
    return minPower;
}
 
int main() {
    cout<<largestPower(7,2)<<endl;
    cout<<largestPower(10,9)<<endl;
    return 0;
}


Java




// Java code of above approach
import java.util.*;
 
class Solution {
 
public static int largestPower(int n, int k) {
// find prime factorization of k and their respective exponents
Map<Integer, Integer> factors = new HashMap<>();
for (int i = 2; i * i <= k; i++) {
while (k % i == 0) {
factors.put(i, factors.getOrDefault(i, 0) + 1);
k /= i;
}
}
if (k > 1) factors.put(k, factors.getOrDefault(k, 0) + 1);
 
    int minPower = Integer.MAX_VALUE;
    // find the largest power of each prime factor and take their minimum
    for (Map.Entry<Integer, Integer> entry : factors.entrySet()) {
        int p = entry.getKey();
        int a = entry.getValue();
        int power = 0;
        for (long i = p; i <= n; i *= p) {
            power += n / i;
        }
        minPower = Math.min(minPower, power / a);
    }
    return minPower;
}
 
  // Driver code
public static void main(String[] args) {
   
  //  calling largest power function
    System.out.println(largestPower(7, 2));
    System.out.println(largestPower(10, 9));
}
}


Python3




import math
 
def largestPower(n, k):
    # find prime factorization of k and their respective exponents
    factors = {}
    i = 2
    while i*i <= k:
        while k % i == 0:
            if i in factors:
                factors[i] += 1
            else:
                factors[i] = 1
            k //= i
        i += 1
    if k > 1:
        if k in factors:
            factors[k] += 1
        else:
            factors[k] = 1
     
    minPower = math.inf
    # find the largest power of each prime factor and take their minimum
    for p, a in factors.items():
        power = 0
        i = p
        while i <= n:
            power += n//i
            i *= p
        minPower = min(minPower, power//a)
     
    return minPower
 
print(largestPower(7,2))
print(largestPower(10,9))


C#




using System;
using System.Collections.Generic;
 
class MainClass {
    static int LargestPower(int n, int k)
    {
        // find prime factorization of k and their
        // respective exponents
        Dictionary<int, int> factors
            = new Dictionary<int, int>();
        for (int i = 2; i * i <= k; i++) {
            while (k % i == 0) {
                if (!factors.ContainsKey(i))
                    factors[i] = 0;
                factors[i]++;
                k /= i;
            }
        }
        if (k > 1 && !factors.ContainsKey(k))
            factors[k] = 1;
        else if (k > 1)
            factors[k]++;
        int minPower = int.MaxValue;
        // find the largest power of each prime factor and
        // take their minimum
        foreach(KeyValuePair<int, int> kvp in factors)
        {
            int p = kvp.Key, a = kvp.Value;
            int power = 0;
            for (long i = p; i <= n; i *= p) {
                power += (int)(n / i);
            }
            minPower = Math.Min(minPower, power / a);
        }
        return minPower;
    }
 
    public static void Main(string[] args)
    {
        Console.WriteLine(LargestPower(7, 2));
        Console.WriteLine(LargestPower(10, 9));
    }
}


Javascript




function largestPower(n, k) {
    // find prime factorization of k and their respective exponents
    let factors = {};
    let i = 2;
    while (i*i <= k) {
        while (k % i === 0) {
            if (factors[i]) {
                factors[i] += 1;
            } else {
                factors[i] = 1;
            }
            k /= i;
        }
        i += 1;
    }
    if (k > 1) {
        if (factors[k]) {
            factors[k] += 1;
        } else {
            factors[k] = 1;
        }
    }
 
    let minPower = Infinity;
    // find the largest power of each prime factor and take their minimum
    for (let p in factors) {
        if (factors.hasOwnProperty(p)) {
            let a = factors[p];
            let power = 0;
            i = p;
            while (i <= n) {
                power += Math.floor(n/i);
                i *= p;
            }
            minPower = Math.min(minPower, Math.floor(power/a));
        }
    }
 
    return minPower;
}
 
console.log(largestPower(7,2));
console.log(largestPower(10,9));


Output

4
2

Time complexity:- O(sqrt(k) + log n).

Auxiliary Space: O(logN)


My Personal Notes arrow_drop_up
Last Updated : 17 Apr, 2023
Like Article
Save Article
Similar Reads
Related Tutorials