
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- Find a number that divides maximum array elements in C++
- Find the last digit when factorial of A divides factorial of B in C++
- Find integers that divides maximum number of elements of the array in C++
- Find sum of digits in factorial of a number in C++
- Maximum number with same digit factorial product in C++
- C++ program to find first digit in factorial of a number
- Find the factorial of a number in pl/sql using C++.
- C++ Program to Find Factorial of a Number using Iteration
- C++ Program to Find Factorial of a Number using Recursion
- Find power of a number using recursion in C#
- Find maximum number that can be formed using digits of a given number in C++
- C++ Program to Find Factorial of a Number using Dynamic Programming
- First digit in factorial of a number in C++
- Java Program to Find Factorial of a number
- Swift Program to Find Factorial of a number

Advertisements