Find maximum power of a number that divides a factorial in C++


Suppose we have two numbers n and fact. We have to find the largest power of n, that divides fact! (factorial of fact). So if fact = 5, and n = 2, then output will be 3. So 5! = 120, and this is divisible by 2^3 = 8.

Here we will use the Legendre’s formula. This finds largest power of a prime, that divides fact!. We will find all prime factors of n, then find largest power of it, that divides fact!.

So if fact is 146, and n = 15, then prime factors of n are 5 and 3. So

for 3, it will be [146/3] + [48/3] + [16/3] + [5/3] + [1/3] = 48 + 16 + 5 + 1 + 0 = 70.

for 5, it will be [146/5] + [29/5] + [5/5] + [1/3] = 29 + 5 + 1 + 0 = 35.

Example

#include<iostream>
#include<cmath>
using namespace std;
int getPowerPrime(int fact, int p) {
   int res = 0;
   while (fact > 0) {
      res += fact / p;
      fact /= p;
   }
   return res;
}
int findMinPower(int fact, int n) {
   int res = INT_MAX;
   for (int i = 2; i <= sqrt(n); i++) {
      int cnt = 0;
      if (n % i == 0) {
         cnt++;
         n = n / i;
      }
      if (cnt > 0) {
         int curr = getPowerPrime(fact, i) / cnt;
         res = min(res, curr);
      }
   }
   if (n >= 2) {
      int curr = getPowerPrime(fact, n);
      res = min(res, curr);
   }
   return res;
}
int main() {
   int fact = 146, n = 5;
   cout << "Minimum power: " << findMinPower(fact, n);
}

Output

Minimum power: 35

Updated on: 18-Dec-2019

179 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements