Suppose we have two integers n and k. We have to find the maximum value of x, such that n! mod (k^x) = 0. So when n = 5, and k = 2, then output will be 3. As n! = 120, now for different values of x, it will be −
120 mod 2^0 = 0, 120 mod 2^1 = 0, 120 mod 2^2 = 0, 120 mod 2^3 = 0, 120 mod 2^4 = 8, 120 mod 2^5 = 24, 120 mod 2^6 = 56, 120 mod 2^7 = 120. As the max value of x = 3, the result is 0, so the output is 3.
To solve this, we have to follow these steps −
#include <iostream> #include <cmath> using namespace std; int calculateMaxX(int n, int k) { int result = n, v, u; int m = sqrt(k) + 1; for (int i = 2; i <= m && k > 1; i++) { if (i == m) { i = k; } for (u = v = 0; k % i == 0; v++) { k /= i; } if (v > 0) { int t = n; while (t > 0) { t /= i; u += t; } result = min(result, u / v); } } return result; } int main() { int n = 5; int k = 2; cout<<"Maximum value of x is: " << calculateMaxX(n, k); }
Maximum value of x is: 3