The Wayback Machine - https://web.archive.org/web/20240930155529/https://www.geeksforgeeks.org/legendres-formula-highest-power-of-prime-number-that-divides-n/
Open In App

Legendre’s formula (Given p and n, find the largest x such that p^x divides n!)

Last Updated : 08 Jan, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Show Topics
Solve Problem
Easy
52.72%
3.1K

Given an integer n and a prime number p, find the largest x such that px (p raised to power x) divides n! (factorial) 
Examples: 

Input:  n = 7, p = 3
Output: x = 2
32 divides 7! and 2 is the largest such power of 3.

Input: n = 10, p = 3
Output: x = 4
34 divides 10! and 4 is the largest such power of 3.

n! is multiplication of {1, 2, 3, 4, …n}.
How many numbers in {1, 2, 3, 4, ….. n} are divisible by p? 
Every p’th number is divisible by p in {1, 2, 3, 4, ….. n}. Therefore in n!, there are ?n/p? numbers divisible by p. So we know that the value of x (largest power of p that divides n!) is at-least ?n/p?. 
Can x be larger than ?n/p? ? 
Yes, there may be numbers which are divisible by p2, p3, … 
How many numbers in {1, 2, 3, 4, ….. n} are divisible by p2, p3, …? 
There are ?n/(p2)? numbers divisible by p2 (Every p2‘th number would be divisible). Similarly, there are ?n/(p3)? numbers divisible by p3 and so on.
What is the largest possible value of x? 
So the largest possible power is ?n/p? + ?n/(p2)? + ?n/(p3)? + …… 
Note that we add only ?n/(p2)? only once (not twice) as one p is already considered by expression ?n/p?. Similarly, we consider ?n/(p3)? (not thrice). 
Below is the implementation of the above idea. 

C++




// C++ program to find largest x such that p*x divides n!
#include <iostream>
using namespace std;
 
// Returns largest power of p that divides n!
int largestPower(int n, int p)
{
    // Initialize result
    int x = 0;
 
    // Calculate x = n/p + n/(p^2) + n/(p^3) + ....
    while (n)
    {
        n /= p;
        x += n;
    }
    return x;
}
 
// Driver code
int main()
{
    int n = 10, p = 3;
    cout << "The largest power of "<< p <<
            " that divides " << n << "! is "<<
            largestPower(n, p) << endl;
    return 0;
}
 
// This code is contributed by shubhamsingh10


C




// C program to find largest x such that p*x divides n!
#include <stdio.h>
 
// Returns largest power of p that divides n!
int largestPower(int n, int p)
{
    // Initialize result
    int x = 0;
 
    // Calculate x = n/p + n/(p^2) + n/(p^3) + ....
    while (n)
    {
        n /= p;
        x += n;
    }
    return x;
}
 
// Driver program
int main()
{
    int n = 10, p = 3;
    printf("The largest power of %d that divides %d! is %d\n",
           p, n, largestPower(n, p));
    return 0;
}


Java




// Java program to find largest x such that p*x divides n!
import java.io.*;
 
class GFG
{
    // Function that returns largest power of p
    // that divides n!
    static int Largestpower(int n, int p)
    {
        // Initialize result
        int ans = 0;
 
        // Calculate x = n/p + n/(p^2) + n/(p^3) + ....
        while (n > 0)
        {
            n /= p;
            ans += n;
        }
        return ans;
    }
 
    // Driver program
    public static void main (String[] args)
    {
        int n = 10;
        int p = 3;
        System.out.println(" The largest power of " + p + " that divides "
                + n + "! is " + Largestpower(n, p));
         
         
    }
}


Python3




# Python3 program to find largest
# x such that p*x divides n!
 
# Returns largest power of p that divides n!
def largestPower(n, p):
     
    # Initialize result
    x = 0
 
    # Calculate x = n/p + n/(p^2) + n/(p^3) + ....
    while n:
        n /= p
        x += n
    return x
 
# Driver program
n = 10; p = 3
print ("The largest power of %d that divides %d! is %d\n"%
                                (p, n, largestPower(n, p)))
         
# This code is contributed by Shreyanshi Arun.


C#




// C# program to find largest x
// such that p * x divides n!
using System;
 
public class GFG
{
     
    // Function that returns largest 
    // power of p that divides n!
    static int Largestpower(int n, int p)
    {
        // Initialize result
        int ans = 0;
 
        // Calculate x = n / p + n / (p ^ 2) +
        // n / (p ^ 3) + ....
        while (n > 0)
        {
            n /= p;
            ans += n;
        }
        return ans;
    }
 
    // Driver Code
    public static void Main ()
    {
        int n = 10;
        int p = 3;
        Console.Write(" The largest power of " + p + " that divides "
                + n + "! is " + Largestpower(n, p));
         
         
    }
}
 
// This code is contributed by Sam007


Javascript




<script>
// Javascript program to find largest
// x such that p*x divides n!
 
// Returns largest power
// of p that divides n!
function largestPower(n, p)
{
    // Initialize result
    let x = 0;
 
    // Calculate x = n/p +
    // n/(p^2) + n/(p^3) + ....
    while (n)
    {
        n = parseInt(n / p);
        x += n;
    }
    return Math.floor(x);
}
 
// Driver Code
let n = 10;
let p = 3;
document.write("The largest power of " + p);
document.write(" that divides " + n + "! is ");
document.write(largestPower(n, p));
     
// This code is contributed by _saurabh_jaiswal
</script>


PHP




<?php
// PHP program to find largest
// x such that p*x divides n!
 
// Returns largest power
// of p that divides n!
function largestPower($n, $p)
{
    // Initialize result
    $x = 0;
 
    // Calculate x = n/p +
    // n/(p^2) + n/(p^3) + ....
    while ($n)
    {
        $n = (int)$n / $p;
        $x += $n;
    }
    return floor($x);
}
 
// Driver Code
$n = 10;
$p = 3;
echo "The largest power of ", $p ;
echo " that divides ",$n , "! is ";
echo largestPower($n, $p);
     
// This code is contributed by ajit
?>


Output

The largest power of 3 that divides 10! is 4

Time complexity: O(logpn)
Auxiliary Space: O(1)
What to do if p is not prime? 
We can find all prime factors of p and compute result for every prime factor. Refer Largest power of k in n! (factorial) where k may not be prime for details.

Approach 2: Using recursion
Another way to implement Legendre’s formula is to use recursion. Here is the code implementation:

  •     Start the program by including the required header files and the standard namespace.
  •    Define a function named largestPower that takes two integers n and p as input and returns an integer.
  •    Check if n is equal to 0. If it is, return 0 as the largest power of p that divides n! is 0.
  •    Calculate the largest power of p that divides n! recursively by dividing n by p and adding the quotient to the result of largestPower(n/p, p).
  •    Return the result of the calculation in step 4.
  •    Define the main function, which sets n equal to 10 and p equal to 3, calls the largestPower function with these values, and outputs the result.
  •    End the program by returning 0 from the main function.

C++




#include<bits/stdc++.h>
using namespace std;
 
int largestPower(int n, int p) {
    if (n == 0) {
        return 0;
    }
    return n/p + largestPower(n/p, p);
}
 
int main() {
    int n = 10, p = 3;
    cout << "The largest power of " << p << " that divides " << n << "! is " << largestPower(n, p) << endl;
    return 0;
}


Java




public class Main {
    public static int largestPower(int n, int p) {
        if (n == 0) {
            return 0;
        }
        return n / p + largestPower(n / p, p);
    }
 
    public static void main(String[] args) {
        int n = 10, p = 3;
        System.out.printf("The largest power of %d that divides %d! is %d", p, n, largestPower(n, p));
    }
}


Python3




def largestPower(n, p):
    if n == 0:
        return 0
    return n // p + largestPower(n // p, p)
 
n, p = 10, 3
print(f"The largest power of {p} that divides {n}! is {largestPower(n, p)}")


C#




using System;
 
public class MainClass {
    public static int largestPower(int n, int p) {
        if (n == 0) {
            return 0;
        }
        // recursively calculate the largest power of p that divides n!
        return n / p + largestPower(n / p, p);
    }
 
    public static void Main(string[] args) {
        int n = 10, p = 3;
        Console.WriteLine("The largest power of {0} that divides {1}! is {2}", p, n, largestPower(n, p));
    }
}


Javascript




function largestPower(n, p) {
    if (n == 0) {
        return 0;
    }
    let x=Math.floor(n/p);
    return x + largestPower(x, p);
}
 
let n = 10, p = 3;
document.write("The largest power of " + p + " that divides " + n + "! is " + largestPower(n, p));


Output

The largest power of 3 that divides 10! is 4

Time complexity: O(logpn)

The time complexity of the largestPower function is O(log_p(n)), where n is the input integer and p is the divisor. This is because the function divides n by p in each recursive call, which reduces the size of n by a factor of p. The number of times the function can be called before n becomes less than p is proportional to the logarithm base p of n. Therefore, the time complexity is O(log_p(n)).

Auxiliary Space: O(logpn)

The space complexity of the function is O(log_p(n)), because each recursive call to the function adds a new stack frame to the call stack, and the depth of the call stack is proportional to the number of times the function is called, which is proportional to the logarithm base p of n. Therefore, the space complexity is O(log_p(n)).
Source: 
http://e-maxx.ru/algo/factorial_divisors

 



Previous Article
Next Article

Similar Reads

Find two co-prime integers such that the first divides A and the second divides B
Given two integers A and B, the task is to find two co-prime numbers C1 and C2 such that C1 divides A and C2 divides B.Examples: Input: A = 12, B = 16 Output: 3 4 12 % 3 = 0 16 % 4 = 0 gcd(3, 4) = 1Input: A = 542, B = 762 Output: 271 381 Recommended: Please try your approach on {IDE} first, before moving on to the solution.Naive approach: A simple
7 min read
Count of triplets (a, b, c) in the Array such that a divides b and b divides c
Given an array arr[] of positive integers of size N, the task is to count number of triplets in the array such that a[i] divides a[j] and a[j] divides a[k] and i < j < k.Examples: Input: arr[] = {1, 2, 3, 4, 5, 6} Output: 3 Explanation: The triplets are: (1, 2, 4), (1, 2, 6), (1, 3, 6).Input: arr[] = {1, 2, 2} Output: 1 Explanation: The tripl
8 min read
Section formula (Point that divides a line in given ratio)
Given two coordinates (x1, y1) and (x2, y2), and m and n, find the co-ordinates that divides the line joining (x1, y1) and (x2, y2) in the ratio m : n  Examples:   Input : x1 = 1, y1 = 0, x2 = 2 y2 = 5, m = 1, n = 1Output : (1.5, 2.5)Explanation: co-ordinates (1.5, 2.5)divides the line in ratio 1 : 1Input : x1 = 2, y1 = 4, x2 = 4, y2 = 6, m = 2, n
5 min read
Largest number that divides x and is co-prime with y
Given two positive numbers x and y. Find the maximum valued integer a such that: a divides x i.e. x % a = 0a and y are co-prime i.e. gcd(a, y) = 1 Examples : Input : x = 15 y = 3 Output : a = 5 Explanation: 5 is the max integer which satisfies both the conditions. 15 % 5 =0 gcd(5, 3) = 1 Hence, output is 5. Input : x = 14 y = 28 Output : a = 1 Expl
6 min read
Legendre's Conjecture
It says that there is always one prime number between any two consecutive natural number's(n = 1, 2, 3, 4, 5, ...) square. This is called Legendre's Conjecture. Conjecture: A conjecture is a proposition or conclusion based upon incomplete information to which no proof has been found i.e it has not been proved or disproved. Mathematically, there is
5 min read
Count of pairs in an array such that the highest power of 2 that divides their product is 1
Given an array arr[] of N positive integers. The task is to find the count of pairs (arr[i], arr[j]) such that the maximum power of 2 that divides arr[i] * arr[j] is 1.Examples: Input: arr[] = {3, 5, 2, 8} Output: 3 (3, 2), (5, 2) and (3, 5) are the only valid pairs. Since the power of 2 that divides 3 * 2 = 6 is 1, 5 * 2 = 10 is 1 and 3 * 5 = 15 i
6 min read
Partitions possible such that the minimum element divides all the other elements of the partition
Given an integer array arr[], the task is to count the number of partitions possible such that in each partition the minimum element divides all the other elements of the partition. The partition need not be continuous.Examples: Input: arr[] = {10, 7, 20, 21, 13} Output: 3 The possible partitions are {10, 20}, {7, 21} and {13}. In each partition, a
6 min read
Find element in array that divides all array elements
Given an array of n non-negative integers. Find such element in the array, that all array elements are divisible by it. Examples : Input : arr[] = {2, 2, 4}Output : 2 Input : arr[] = {2, 1, 3, 1, 6}Output : 1 Input: arr[] = {2, 3, 5}Output : -1 Brute Force Approach: The brute force approach to solve this problem would be to iterate through all the
7 min read
Find an element which divides the array in two subarrays with equal product
Given, an array of size N. Find an element which divides the array into two sub-arrays with equal product. Print -1 if no such partition is not possible. Examples : Input : 1 4 2 1 4 Output : 2 If 2 is the partition, subarrays are : {1, 4} and {1, 4} Input : 2, 3, 4, 1, 4, 6 Output : 1 If 1 is the partition, Subarrays are : {2, 3, 4} and {4, 6} A s
12 min read
Find a number that divides maximum array elements
Given an array A[] of N non-negative integers. Find an Integer greater than 1, such that maximum array elements are divisible by it. In case of same answer print the smaller one. Examples: Input : A[] = { 2, 4, 5, 10, 8, 15, 16 }; Output : 2 Explanation: 2 divides [ 2, 4, 10, 8, 16] no other element divides greater than 5 numbers.' Input : A[] = {
13 min read
Find integers that divides maximum number of elements of the array
Given an array arr[] of integers, the task is to find the element (other than 1) which is the factor of the maximum number of elements in the array. If multiple such factors exist, print all the factors in ascending order. Examples: Input: arr[] = {10, 20} Output: 2 5 10 The factors of 10 are 1, 2, 5, 10. The factors of 20 are 1, 2, 4, 5, 10, 20. T
7 min read
Find the index of the element in an array which divides most elements before it
Given an array arr, the task is to find the index of the element in an array which divides most elements before itExamples: Input: arr = {5, 2, 1, 4, 5, 8, 2} Output: 6 Explanation arr[6] = 2 it divides 2, 4, and 8 (3 elements) Input: arr = {8, 1, 28, 4, 1, 6, 7} Output: 4 Approach: Maintain a map.For each arr[i] update the count variable by lookin
6 min read
Find the Smallest number that divides X^X
Given a number X, find the Smallest Number, which is greater than 1, that divides XX. In the given question, X is always presumed to be greater than 1.Examples: Input: X = 6 Output: 2 Explanation: As, 66 is equal to 46656, which is divisible by 2 and it's the smallest among all its divisors. Input: X = 3 Output: 3 Explanation: As, 33 is equal to 27
4 min read
Find maximum power of a number that divides a factorial
Given two numbers, fact and n, find the largest power of n that divides fact! (Factorial of fact). Examples: Input : fact = 5, n = 2 Output : 3 Explanation: Value of 5! is 120. The largest power of 2 that divides 120 is 8 (or 23 Input : fact = 146, n = 15 Output : 35 The idea is based on Legendre’s formula which finds largest power of a prime numbe
12 min read
Find the last digit when factorial of A divides factorial of B
We are given two numbers A and B such that B >= A. We need to compute the last digit of this resulting F such that F = B!/A! where 1 = A, B <= 10^18 (A and B are very large).Examples: Input : A = 2, B = 4Output : 2Explanation : A! = 2 and B! = 24. F = 24/2 = 12 --> last digit = 2Input : 107 109Output : 2As we know, factorial function grows
10 min read
Highest power of two that divides a given number
Given a number n, find the highest power of 2 that divides n.Examples: Input : n = 48 Output : 16 Highest power of 2 that divides 48 is 16.Input : n = 5 Output : 1 Highest power of 2 that divides 5 is 1. A simple solution is to try all powers of 2 one by one starting from 1, then 2, then 4 and so on.An efficient solution is based on bit magic. If w
5 min read
Check if a given number divides the sum of the factorials of its digits
Given an integer N, the task is to check whether N divides the sum of the factorials of its digits. Examples: Input: N = 19 Output: Yes 1! + 9! = 1 + 362880 = 362881, which is divisible by 19. Input: N = 20 Output: No 0! + 2! = 1 + 4 = 5, which is not divisible by 20. Recommended: Please try your approach on {IDE} first, before moving on to the sol
9 min read
Minimum value that divides one number and divisible by other
Given two integer p and q, the task is to find the minimum possible number x such that q % x = 0 and x % p = 0. If the conditions aren't true for any number then print -1.Examples: Input: p = 3, q = 99 Output: 3 99 % 3 = 0 3 % 3 = 0Input: p = 2, q = 7 Output: -1 Approach: If a number x satisfies the given condition then it's obvious that q will be
4 min read
Check if a M-th fibonacci number divides N-th fibonacci number
Given two numbers M and N, the task is to check if the M-th and N-th Fibonacci numbers perfectly divide each other or not.Examples: Input: M = 3, N = 6 Output: Yes F(3) = 2, F(6) = 8 and F(6) % F(3) = 0 Input: M = 2, N = 9 Output: Yes A naive approach will be to find the N-th and M-th Fibonacci numbers and check if they are perfectly divisible or n
8 min read
Check if the sum of digits of a number N divides it
Given a number N. The task is to check if the sum of digits of the given number divides the number or not. If it divides it then print YES otherwise print NO.Examples: Input : N = 12Output : YESSum of digits = 1+2 =3 and 3 divides 12.So, print YES.Input : N = 15Output : NORecommended: Please try your approach on {IDE} first, before moving on to the
10 min read
Highest power of 2 that divides a number represented in binary
Given binary string str, the task is to find the largest power of 2 that divides the decimal equivalent of the given binary number. Examples: Input: str = "100100" Output: 2 22 = 4 is the highest power of 2 that divides 36 (100100).Input: str = "10010" Output: 1 Approach: Starting from the right, count the number of 0s in the binary representation
4 min read
Count of numbers from the range [L, R] which contains at least one digit that divides K
Given three positive integers L, R and K.The task is to find the count of all the numbers from the range [L, R] that contains at least one digit which divides the number K. Examples: Input: L = 5, R = 11, K = 10 Output: 3 5, 10 and 11 are only such numbers. Input: L = 32, R = 38, K = 13 Output: 0 Approach: Initialise count = 0 and for every element
6 min read
Count of prime digits of a Number which divides the number
Given an integer N, the task is to count the number of digits in N which is a prime number, and also divides the number.Examples: Input: N = 12 Output: 1 Explanation: Digits of the number = {1, 2} But, only 2 is prime number that divides N.Input: N = 1032 Output: 2 Explanation: Digits of the number = {1, 0, 3, 2} 3 and 2 divides the number and are
6 min read
Check if max sum level of Binary tree divides tree into two equal sum halves
Given a Binary Tree, the task is to check if the maximum sum level divides the binary tree into the two parts of two equal sum halves.Examples: Input: 1 / \ 2 3 / \ \ 4 5 8 / \ 2 4 Output: YES Explanation: The maximum sum level is 2 and its sum is (4 + 5 + 8 = 17) Sum of the upper half (1 + 2 + 3) = 6 Sum of the Lower half (2 + 4) = 6 Input: 10 / \
11 min read
Highest power of 2 that divides the LCM of first N Natural numbers.
Given a number N, the task is to find the largest power of 2 that divides LCM of first N Natural numbers. Examples: Input: N = 5Output: 2Explanation:LCM of {1, 2, 3, 4, 5} = 6060 is divisible by 22 Input: N = 15 Output: 3Explanation:LCM of {1, 2, 3.....14, 15} = 360360360360 is divisible by 23 Naive Approach: The idea is to find the Least common mu
8 min read
Smallest positive integer that divides all array elements to generate quotients with sum not exceeding K
Given an array arr[] of size N and a positive integer K, the task is to find the smallest positive integer such that the sum of remaining array elements obtained by dividing all array elements by that smallest positive integer does not exceed K. Note: Dividing an array element by the smallest positive integer must be of Ceil type. Examples: Input:
8 min read
Minimize the sum of pair which upon removing divides the Array into 3 subarrays
Given an array arr of size N, the task is to find pair of elements having minimum sum, which on removal breaks the array into 3 non-empty subarrays of the original array. Print the sum of the elements in this pair. Input: arr[]: {4, 2, 1, 2, 4}Output: 4Explanation:Minimum sum pairs are values (2, 1) and (1, 2) but selecting a pair with adjacent ind
6 min read
Highest power of a number that divides other number | Set - 2
Given two numbers N and M(M > 1), the task is to find the highest power of M that divides N. Examples: Input: N = 12, M = 2Output: 2Explanation: The powers of 2 which divide 12 are 1 and 2 (21 = 2 and 22 = 4 which both divide 12). The higher power is 2, hence consider 2. Input: N = 500, M = 5Output: 3. Naive and Bit Manipulation Approach: The na
5 min read
Count of distinct coprime pairs product of which divides all elements in index [L, R] for Q queries
Given an array arr[] of N integers and Q queries of the form (l, r). The task is to find the number of distinct pairs of coprime integers for each query such that all integers in index range [l, r] are divisible by the product of the coprime integers. Examples: Input: arr[] = {1, 2, 2, 4, 5}, queries[] = {{2, 3}, {2, 4}, {3, 4}, {4, 4}, {4, 5}}Outp
15 min read
Highest power of a number that divides other number
Given two numbers N and M, the task is to find the highest power of M that divides N. Note: M > 1 Examples: Input: N = 48, M = 4 Output: 2 48 % (4^2) = 0 Input: N = 32, M = 20 Output: 0 32 % (20^0) = 0 Brute Force Approach: The idea to solve this problem is to iterate from 1 to m and for each number, check if it is a factor of both n and m. If i
15+ min read