Given two integers and . The task is to find the maximum value of x, such that, n! % (k^x) = 0.
Input : n = 5, k = 2 Output : 3 Explanation : Given n = 5 and k = 2. So, n! = 120. Now for different values of x: n! % 2^0 = 0, n! % 2^1 = 0, n! % 2^2 = 0, n! % 2^3 = 0, n! % 2^4 = 8, n! % 2^5 = 24, n! % 2^6 = 56, n! % 2^7 = 120. So, the answer should be 3. Input : n = 1000, x = 2 Output : 994
- First take the squareroot of and store it in a variable say, .
- Run the loop from i=2 to m.
- If i = m then copy k to i.
- If k is divisible by i then divide k by i.
- Run a loop to n and add the quotient to a varible say, .
- Store the minimum value of r after every loop.
Below is the implementation of the above approach:
if ($i == $m)
$i = $k;
// optimize the value of k
for ($u = $v = 0; $k % $i == 0; $v++)
$k = (int)($k / $i);
if ($v > 0)
$t = $n;
while ($t > 0)
$t = (int)($t / $i);
$u = $u + $t;
// Minimum store
$r = min($r, (int)($u / $v));
// Driver Code
$n = 5;
$k = 2;
echo findX($n, $k);
// This code is contributed by
- Find maximum among x^(y^2) or y^(x^2) where x and y are given
- Find the maximum possible value of a[i] % a[j] over all pairs of i and j
- Find pair with maximum GCD in an array
- Find a pair from the given array with maximum nCr value
- Find Sum of pair from two arrays with maximum sum
- Find maximum element of each row in a matrix
- Find triplets in an array whose AND is maximum
- Find three integers less than or equal to N such that their LCM is maximum
- Find a positive number M such that gcd(N^M, N&M) is maximum
- Find maximum operations to reduce N to 1
- Find the maximum number of handshakes
- Find the maximum length of the prefix
- Find the node whose sum with X has maximum set bits
- Given count of digits 1, 2, 3, 4, find the maximum sum possible
- Find prime number K in an array such that (A[i] % K) is maximum
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.