Find the first natural number whose factorial is divisible by x in C++


We have to find the first natural number whose factorial is divisible by x. The x is given by the user. So if the x = 16, then output will be 6. as 6! mod 16 = 0. We will use general approach to solve this problem. iteratively count 1!, 2!, …. n! and check divisibility using x. If modulus is 0, then stop and return the number.

Example

 Live Demo

#include<iostream>
using namespace std;
int getNumber(int x) {
   int fact = 1;
   int i = 0;
   while(fact % x != 0){
      i++;
      fact = fact * i;
   }
   return i;
}
int main() {
   int x = 16;
   cout << "Minimum value of N is: " << getNumber(x);
}

Output

Minimum value of N is: 6

Updated on: 19-Dec-2019

141 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements