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

C++Server Side ProgrammingProgramming

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
raja
Published on 18-Dec-2019 11:26:52
Advertisements