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

Last Updated : 17 Nov, 2025

Given two positive integers k and n, where k > 1, find the largest power of k that divides n! (n factorial).

Examples: 

Input: n = 7, k = 2
Output: 4
Explanation: 7! = 5040, and 2^4 = 16 is the highest power of 2 that divides 5040.

Input: n = 10, k = 9
Output: 2
Explanation: 10! = 3628800, and 9^2 = 81 is the highest power of 9 that divides 3628800.

Try It Yourself
redirect icon

[Naive Approach] Factorial Division Method O(n) Time and O(1) Space

This approach first computes n! explicitly, then repeatedly divides it by k to count how many times k divides n!.

Note: This approach does not work for large values of n, because computing n! directly causes integer overflow.

Factorials grow very rapidly, and for even moderately large n (e.g., n > 20), the value of n! can exceed the range of standard data types.

C++
#include<iostream>
using namespace std;

// Function to compute the factorial of a number
int computeFac(int number) {
    int factorial = 1;
    
    // Multiply all integers from 1 to 'number'
    for (int i = 1; i <= number; i++) {
        factorial *= i;
    }
    return factorial;
}

// Function to find the maximum exponent 
// 'power' such that k^power divides n!
int maxKPower(int n, int k) {
    
    int facOfN = computeFac(n);

    int power = 0;
    
    // Repeatedly divide factorial by k 
    // as long as divisible
    while (facOfN % k == 0) {
        power++;
        facOfN /= k;
    }

    return power;
}

int main() {

    int n = 10, k = 9;
    cout << maxKPower(n, k) << endl;

    return 0;
}
Java
class GfG {
    
    // Function to compute the factorial of a number
    static int computeFac(int number) {
        int factorial = 1;
        // Multiply all integers from 1 to 'number'
        for (int i = 1; i <= number; i++) {
            factorial *= i;
        }
        return factorial;
    }

    // Function to find the maximum exponent 
    // 'power' such that k^power divides n!
    static int maxKPower(int n, int k) {

        int facOfN = computeFac(n);

        int power = 0;
        
        // Repeatedly divide factorial by k 
        // as long as divisible
        while (facOfN % k == 0) {
            power++;
            facOfN /= k;
        }

        return power;
    }

    public static void main(String[] args) {

        int n = 10, k = 9;
        System.out.println(maxKPower(n, k));
        
    }
}
Python
# Function to compute the factorial of a number
def computeFac(number):
    factorial = 1
    
    # Multiply all integers from 1 to 'number'
    for i in range(1, number + 1):
        factorial *= i
    return factorial

# Function to find the maximum exponent 
# 'power' such that k^power divides n!
def maxKPower(n, k):
    facOfN = computeFac(n)

    power = 0
    
    # Repeatedly divide factorial by k 
    # as long as divisible
    while facOfN % k == 0:
        power += 1
        facOfN //= k

    return power

if __name__ == "__main__":
    n = 10
    k = 9
    print(maxKPower(n, k))
C#
using System;

class GfG
{
    // Function to compute the factorial of a number
    static int computeFac(int number)
    {
        int factorial = 1;
        
        // Multiply all integers from 1 to 'number'
        for (int i = 1; i <= number; i++)
        {
            factorial *= i;
        }
        return factorial;
    }

    // Function to find the maximum exponent 
    // 'power' such that k^power divides n!
    static int maxKPower(int n, int k)
    {
        int facOfN = computeFac(n);

        int power = 0;
        
        // Repeatedly divide factorial by k 
        // as long as divisible
        while (facOfN % k == 0)
        {
            power++;
            facOfN /= k;
        }

        return power;
    }

    public static void Main()
    {
        int n = 10, k = 9;
        Console.WriteLine(maxKPower(n, k));
    }
}
JavaScript
// Function to compute the factorial of a number
function computeFac(number) {
    let factorial = 1;
    
    // Multiply all integers from 1 to 'number'
    for (let i = 1; i <= number; i++) {
        factorial *= i;
    }
    return factorial;
}

// Function to find the maximum exponent 
// 'power' such that k^power divides n!
function maxKPower(n, k) {
    let facOfN = computeFac(n);

    let power = 0;
    
    // Repeatedly divide factorial by k 
    // as long as divisible
    while (facOfN % k === 0) {
        power++;
        facOfN /= k;
    }

    return power;
}

// Driver Code
let n = 10, k = 9;
console.log(maxKPower(n, k));

Output
2

[Better Approach] Prime Count in Factorial Approach

Factorize k into its prime components, then for each prime, naively count its total occurrences in n! by checking every number from 1 to n.
Finally, compute how many times k can divide n! by dividing the total count by the prime’s exponent in k.

Step By Step Implementations

  • Since final rem = 0, the number 2911285 is divisible by 13.
  • Factorize the number k into its prime factors with their respective exponents.
  • For each prime factor p of k, iterate from 1 to n.
  • For each number i from 1 to n, count how many times p divides i.
    → Keep a running total of how many times p appears in the factorization of n!.
  • After counting, divide the total count of p by its exponent in k.
    → This gives how many times pexp (from k) can divide n!.
  • Do this for all prime factors of k, and take the minimum among these results.
    → That minimum is the largest power x such that kx divides n!.
C++
#include <iostream>
#include <vector>
#include <climits>

using namespace std;

// Function to compute the prime 
// factorization of a number 'num'
vector<vector<int>> primeFactors(int num) {
    vector<vector<int>> factors;

    // Count the number of times 2 divides 'num'
    int count = 0;
    while (num % 2 == 0) {
        num /= 2;
        count++;
    }
    if (count > 0) factors.push_back({2, count});

    // Check for odd factors starting from 3
    for (int i = 3; i * i <= num; i += 2) {
        count = 0;
        while (num % i == 0) {
            num /= i;
            count++;
        }
        if (count > 0) factors.push_back({i, count});
    }

    // If 'num' is still greater than 1, it's a prime number
    if (num > 1) factors.push_back({num, 1});

    return factors;
}

int maxKPower(int n, int k) {
    vector<vector<int>> factors = primeFactors(k);

    // Initialize result to maximum possible, we'll 
    // take the minimum across all primes
    int result = INT_MAX;

    // For each prime factor of k
    for (auto &factor : factors) {

        int prime = factor[0];
        int freqInK = factor[1];
        
        int count = 0;

        // Count how many times 'prime' appears 
        // in the factorization of n!
        for (int i = 1; i <= n; i++) {
            int x = i;
            
            // Count how many times 'prime' divides 
            // this particular number
            while (x % prime == 0) {
                count++;
                x /= prime;
            }
        }

        // Since k = prime^freqInK × ..., 
        // we divide the total count by freqInK
        result = min(result, count / freqInK);
    }

    return result;
}

int main() {

    int n = 10, k = 9;
    cout << maxKPower(n, k) << '\n'; 

    return 0;
}
Java
import java.util.*;

class GfG {

    // Function to compute prime factorization of k
    public static ArrayList<ArrayList<Integer>> primeFactors(int num) {
        ArrayList<ArrayList<Integer>> factors = new ArrayList<>();

        int count = 0;
        while (num % 2 == 0) {
            num /= 2;
            count++;
        }
        if (count > 0) {
            ArrayList<Integer> pair = new ArrayList<>();
            pair.add(2);
            pair.add(count);
            factors.add(pair);
        }

        for (int i = 3; i * i <= num; i += 2) {
            count = 0;
            while (num % i == 0) {
                num /= i;
                count++;
            }
            if (count > 0) {
                ArrayList<Integer> pair = new ArrayList<>();
                pair.add(i);
                pair.add(count);
                factors.add(pair);
            }
        }

        if (num > 1) {
            ArrayList<Integer> pair = new ArrayList<>();
            pair.add(num);
            pair.add(1);
            factors.add(pair);
        }

        return factors;
    }

    // Function to find the largest power of k that divides n!
    public static int maxKPower(int n, int k) {
        ArrayList<ArrayList<Integer>> factors = primeFactors(k);
        int result = Integer.MAX_VALUE;

        for (ArrayList<Integer> factor : factors) {
            int prime = factor.get(0);
            int freqInK = factor.get(1);
            int count = 0;

            // Naively count how many times 'prime' appears in n!
            for (int i = 1; i <= n; i++) {
                int x = i;
                while (x % prime == 0) {
                    count++;
                    x /= prime;
                }
            }

            // Divide count by the exponent in k
            result = Math.min(result, count / freqInK);
        }

        return result;
    }

    public static void main(String[] args) {
        int n = 10, k = 9;
        System.out.println(maxKPower(n, k)); 
    }
}
Python
def primeFactors(num):
    # Function to compute the prime
    # factorization of a number 'num'
    factors = []

    # Count the number of times 2 divides 'num'
    count = 0
    while num % 2 == 0:
        num //= 2
        count += 1
    if count > 0:
        factors.append([2, count])

    # Check for odd factors starting from 3
    i = 3
    while i * i <= num:
        count = 0
        while num % i == 0:
            num //= i
            count += 1
        if count > 0:
            factors.append([i, count])
        i += 2

    # If 'num' is still greater than 1, it's a prime number
    if num > 1:
        factors.append([num, 1])

    return factors


def maxKPower(n, k):
    # Step 1: Get the prime factorization of k
    factors = primeFactors(k)

    # Initialize result to maximum possible, we'll
    # take the minimum across all primes
    result = float('inf')

    # For each prime factor of k
    for prime, freq_in_k in factors:
        count = 0

        # Count how many times 'prime' appears
        # in the factorization of n!
        for i in range(1, n + 1):
            x = i
            # Count how many times 'prime' divides
            # this particular number
            while x % prime == 0:
                count += 1
                x //= prime

        # Since k = prime^freq_in_k × ...,
        # we divide the total count by freq_in_k
        result = min(result, count // freq_in_k)

    return result


if __name__ == "__main__":
    n = 10
    k = 9
    print(maxKPower(n, k)) 
C#
using System;
using System.Collections.Generic;

class GfG
{
    // Function to compute the prime 
    // factorization of a number 'num'
    public static int[,] primeFactors(int num)
    {
        List<int[]> tempFactors = new List<int[]>();

        int count = 0;
        while (num % 2 == 0)
        {
            num /= 2;
            count++;
        }
        if (count > 0)
            tempFactors.Add(new int[] { 2, count });

        // Check for odd factors starting from 3
        for (int i = 3; i * i <= num; i += 2)
        {
            count = 0;
            while (num % i == 0)
            {
                num /= i;
                count++;
            }
            if (count > 0)
                tempFactors.Add(new int[] { i, count });
        }

        // If 'num' is still greater than 1, it's a prime number
        if (num > 1)
            tempFactors.Add(new int[] { num, 1 });

        // Convert List<int[]> to 2D array
        int[,] factors = new int[tempFactors.Count, 2];
        for (int i = 0; i < tempFactors.Count; i++)
        {
            factors[i, 0] = tempFactors[i][0];
            factors[i, 1] = tempFactors[i][1];
        }

        return factors;
    }

    public static int maxKPower(int n, int k)
    {
        int[,] factors = primeFactors(k);

        int result = int.MaxValue;

        int numFactors = factors.GetLength(0);

        // For each prime factor of k
        for (int i = 0; i < numFactors; i++)
        {
            int prime = factors[i, 0];
            int freqInK = factors[i, 1];
            int count = 0;

            // Count how many times 'prime' appears 
            // in the factorization of n!
            for (int j = 1; j <= n; j++)
            {
                int x = j;
                while (x % prime == 0)
                {
                    count++;
                    x /= prime;
                }
            }

            // Divide the count by the exponent in k
            result = Math.Min(result, count / freqInK);
        }

        return result;
    }

    public static void Main()
    {
        int n = 10, k = 9;
        Console.WriteLine(maxKPower(n, k));
    }
}
JavaScript
// Function to compute the prime 
// factorization of a number 'num'
function primeFactors(num) {
    let factors = [];

    // Count the number of times 2 divides 'num'
    let count = 0;
    while (num % 2 === 0) {
        num = Math.floor(num / 2);
        count++;
    }
    if (count > 0) factors.push([2, count]);

    // Check for odd factors starting from 3
    for (let i = 3; i * i <= num; i += 2) {
        count = 0;
        while (num % i === 0) {
            num = Math.floor(num / i);
            count++;
        }
        if (count > 0) factors.push([i, count]);
    }

    // If 'num' is still greater than 1, it's a prime number
    if (num > 1) factors.push([num, 1]);

    return factors;
}

function maxKPower(n, k) {
    let factors = primeFactors(k);

    // Initialize result to maximum possible, we'll 
    // take the minimum across all primes
    let result = Infinity;

    // For each prime factor of k
    for (let [prime, freqInK] of factors) {
        let count = 0;

        // Count how many times 'prime' appears 
        // in the factorization of n!
        for (let i = 1; i <= n; i++) {
            let x = i;
            // Count how many times 'prime' divides 
            // this particular number
            while (x % prime === 0) {
                count++;
                x = Math.floor(x / prime);
            }
        }

        // Since k = prime^freqInK × ..., 
        // we divide the total count by freqInK
        result = Math.min(result, Math.floor(count / freqInK));
    }

    return result;
}

// Driver code
let n = 10, k = 9;
console.log(maxKPower(n, k));

Output
2

Time Complexity: O(√k + m × n log n), O(√k) for factorization and O(m × n log n) for counting divisions, where m is the number of prime factors of k (m is nearly equal to log k).
Auxiliary Space: O(log k) for unique prime factors the factors of k.

[Expected Approach] Legendre’s Method for Composite Divisibility

When p is a prime number, we can use Legendre’s formula to find the highest power of p that divides n!. The formula calculates this power as:

\left\lfloor \frac{n}{p} \right\rfloor + \left\lfloor \frac{n}{p^2} \right\rfloor + \left\lfloor \frac{n}{p^3} \right\rfloor + \dots

Since k may not be a prime number, we begin by factorizing it into its prime components, along with their respective exponents. For each prime factor p, we apply Legendre’s formula to calculate how many times p appears in the factorization of n!. We then divide this count by the exponent of p in k. The minimum of these values across all prime factors gives the largest power of k that divides n!

Step by step approach:

  • Factorize k into its prime factors along with their exponents.
  • For each prime p in the factorization, calculate how many times p appears in the factorization of n! using:
    • \text{count}_p = \left\lfloor \frac{n}{p} \right\rfloor + \left\lfloor \frac{n}{p^2} \right\rfloor + \left\lfloor \frac{n}{p^3} \right\rfloor + \left\lfloor \frac{n}{p^4} \right\rfloor + \cdots
  • Divide the total count of p in n! by its exponent in k to find how many times this prime allows k to divide n!
  • Repeat this for all prime factors of k
  • Return the minimum value among all these divisions — this is the largest power x such that kx divides n!
C++
#include <iostream>
#include <vector>
#include <climits>
using namespace std;

// Function to compute the prime 
// factorization of a number 'num'
vector<vector<int>> primeFactors(int num) {
    vector<vector<int>> factors;

    int count = 0;
    while (num % 2 == 0) {
        num /= 2;
        count++;
    }
    if (count > 0)
        factors.push_back({2, count});

    // Check for odd factors starting from 3
    for (int i = 3; i * i <= num; i += 2) {
        count = 0;
        while (num % i == 0) {
            num /= i;
            count++;
        }
        if (count > 0)
            factors.push_back({i, count});
    }

    // If 'num' is still greater than 1, 
    // it's a prime number
    if (num > 1)
        factors.push_back({num, 1});

    return factors;
}

// Function to compute how many times prime p 
// appears in n! using Legendre's formula
int legendre(int n, int p) {
    int count = 0;
    for (int power = p; power <= n; power *= p) {
        count += n / power;
    }
    return count;
}

// Function to find the largest power of k that divides n!
int maxKPower(int n, int k) {

    vector<vector<int>> factors = primeFactors(k);

    int result = INT_MAX;

    for (auto &factor : factors) {
        int prime = factor[0];
        int expInK = factor[1];

        // Count total exponent of 'prime' in n!
        // using Legendre’s formula
        int countInFact = legendre(n, prime);

        // Divide by its exponent in k
        result = min(result, countInFact / expInK);
    }

    return result;
}

int main() {
    
    int n = 10, k = 9;
    cout << maxKPower(n, k) << '\n'; 

    return 0;
}
Java
import java.util.*;

class GfG {

    // Function to compute the prime 
    // factorization of a number 'num'
    public static ArrayList<int[]> primeFactors(int num) {
        ArrayList<int[]> factors = new ArrayList<>();

        int count = 0;
        while (num % 2 == 0) {
            num /= 2;
            count++;
        }
        if (count > 0)
            factors.add(new int[]{2, count});

        // Check for odd factors starting from 3
        for (int i = 3; i * i <= num; i += 2) {
            count = 0;
            while (num % i == 0) {
                num /= i;
                count++;
            }
            if (count > 0)
                factors.add(new int[]{i, count});
        }

        // If 'num' is still greater than 1, 
        // it's a prime number
        if (num > 1)
            factors.add(new int[]{num, 1});

        return factors;
    }

    // Function to compute how many times prime p 
    // appears in n! using Legendre's formula
    public static int legendre(int n, int p) {
        int count = 0;
        for (long power = p; power <= n; power *= p) {
            count += n / power;
        }
        return count;
    }

    // Function to find the largest power of k that divides n!
    public static int maxKPower(int n, int k) {
        ArrayList<int[]> factors = primeFactors(k);

        int result = Integer.MAX_VALUE;

        // For each prime factor of k
        for (int[] factor : factors) {
            int prime = factor[0];
            int expInK = factor[1];

            // Count total exponent of 'prime' in n! 
            // using Legendre’s formula
            int countInFact = legendre(n, prime);

            // Divide by its exponent in k
            result = Math.min(result, countInFact / expInK);
        }

        return result;
    }

    public static void main(String[] args) {
        int n = 10, k = 9;
        System.out.println(maxKPower(n, k));
    }
}
Python
import math

# Function to compute the prime 
# factorization of a number 'num'
def primeFactors(num):
    factors = []

    count = 0
    while num % 2 == 0:
        num //= 2
        count += 1
    if count > 0:
        factors.append([2, count])

    # Check for odd factors starting from 3
    i = 3
    while i * i <= num:
        count = 0
        while num % i == 0:
            num //= i
            count += 1
        if count > 0:
            factors.append([i, count])
        i += 2

    # If 'num' is still greater than 1, 
    # it's a prime number
    if num > 1:
        factors.append([num, 1])

    return factors

# Function to compute how many times prime p 
# appears in n! using Legendre's formula
def legendre(n, p):
    count = 0
    power = p
    while power <= n:
        count += n // power
        power *= p
    return count

# Function to find the largest power 
# of k that divides n!
def maxKPower(n, k):
    factors = primeFactors(k)
    result = float('inf')

    for prime, expInK in factors:
        
        # Count total exponent of 'prime' in n! 
        # using Legendre’s formula
        countInFact = legendre(n, prime)

        # Divide by its exponent in k
        result = min(result, countInFact // expInK)

    return result

if __name__ == "__main__":
    n = 10
    k = 9
    print(maxKPower(n, k))
C#
using System;
using System.Collections.Generic;

class GfG
{
    // Function to compute the prime 
    // factorization of a number 'num'
    public static int[,] primeFactors(int num)
    {
        List<int[]> tempFactors = new List<int[]>();

        int count = 0;
        while (num % 2 == 0)
        {
            num /= 2;
            count++;
        }
        if (count > 0)
            tempFactors.Add(new int[] { 2, count });

        // Check for odd factors starting from 3
        for (int i = 3; i * i <= num; i += 2)
        {
            count = 0;
            while (num % i == 0)
            {
                num /= i;
                count++;
            }
            if (count > 0)
                tempFactors.Add(new int[] { i, count });
        }

        // If 'num' is still greater than 1, it's a prime number
        if (num > 1)
            tempFactors.Add(new int[] { num, 1 });

        // Convert to 2D array
        int[,] factors = new int[tempFactors.Count, 2];
        for (int i = 0; i < tempFactors.Count; i++)
        {
            factors[i, 0] = tempFactors[i][0];
            factors[i, 1] = tempFactors[i][1];
        }

        return factors;
    }

    // Function to compute how many times prime p 
    // appears in n! using Legendre's formula
    public static int legendre(int n, int p)
    {
        int count = 0;
        long power = p;
        while (power <= n)
        {
            count += n / (int)power;
            power *= p;
        }
        return count;
    }

    // Function to find the largest power of k that divides n!
    public static int maxKPower(int n, int k)
    {
        int[,] factors = primeFactors(k);
        int result = int.MaxValue;

        int len = factors.GetLength(0); // number of rows

        for (int i = 0; i < len; i++)
        {
            int prime = factors[i, 0];
            int expInK = factors[i, 1];

            // Count total exponent of 'prime' in n! using Legendre’s formula
            int countInFact = legendre(n, prime);

            // Divide by its exponent in k
            result = Math.Min(result, countInFact / expInK);
        }

        return result;
    }

    public static void Main()
    {
        int n = 10, k = 9;
        Console.WriteLine(maxKPower(n, k));
    }
}
JavaScript
// Function to compute the prime 
// factorization of a number 'num'

function primeFactors(num) {
    const factors = [];

    let count = 0;
    while (num % 2 === 0) {
        num = Math.floor(num / 2);
        count++;
    }
    if (count > 0)
        factors.push([2, count]);

    // Check for odd factors starting from 3
    for (let i = 3; i * i <= num; i += 2) {
        count = 0;
        while (num % i === 0) {
            num = Math.floor(num / i);
            count++;
        }
        if (count > 0)
            factors.push([i, count]);
    }

    // If 'num' is still greater than 1, 
    // it's a prime number
    if (num > 1)
        factors.push([num, 1]);

    return factors;
}

// Function to compute how many times prime p 
// appears in n! using Legendre's formula
function legendre(n, p) {
    let count = 0;
    let power = p;
    while (power <= n) {
        count += Math.floor(n / power);
        power *= p;
    }
    return count;
}

// Function to find the largest power of k that divides n!
function maxKPower(n, k) {
    const factors = primeFactors(k);
    let result = Infinity;

    for (const [prime, expInK] of factors) {
        
        // Count total exponent of 'prime' in n! 
        // using Legendre’s formula
        const countInFact = legendre(n, prime);

        // Divide by its exponent in k
        result = Math.min(result, Math.floor(countInFact / expInK));
    }

    return result;
}

// Driver Code
const n = 10, k = 9;
console.log(maxKPower(n, k)); 

Output
2

Time Complexity: O(√k + m * log n), where m is number of distinct prime factors in k, O(√k) for prime factorization of k and log n for apply Legendre formula for each prime factor of k.
Auxiliary Space: O(m), where m is number of distinct prime factors in

Comment