
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find maximum value of x such that n! % (k^x) = 0 in C++
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 −
- Take the square root of k, and store it into m
- For i := 2 to m, do the following steps:
- When i = m, then set i := k
- if k is divisible by i, then, divide k by i
- Run a loop to n, and add quotient to a variable called u.
- Store the min value of r, after each loop
Example
#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); }
Output
Maximum value of x is: 3
Advertisements