Given a number x, the task is to find first natural number i whose factorial is divisible by x.
Examples :
Input : x = 10
Output : 5
5 is the smallest number such that
(5!) % 10 = 0
Input : x = 16
Output : 6
6 is the smallest number such that
(6!) % 16 = 0
A simple solution is to iterate from 1 to x-1 and for every number i check if i! is divisible by x.
C++
#include <bits/stdc++.h>
using namespace std;
int firstFactorialDivisibleNumber( int x)
{
int i = 1;
int fact = 1;
for (i = 1; i < x; i++) {
fact = fact * i;
if (fact % x == 0)
break ;
}
return i;
}
int main( void )
{
int x = 16;
cout << firstFactorialDivisibleNumber(x);
return 0;
}
|
Java
class GFG {
static int firstFactorialDivisibleNumber( int x)
{
int i = 1 ;
int fact = 1 ;
for (i = 1 ; i < x; i++) {
fact = fact * i;
if (fact % x == 0 )
break ;
}
return i;
}
public static void main(String[] args)
{
int x = 16 ;
System.out.print(firstFactorialDivisibleNumber(x));
}
}
|
Python3
def firstFactorialDivisibleNumber(x):
i = 1 ;
fact = 1 ;
for i in range ( 1 , x):
fact = fact * i
if (fact % x = = 0 ):
break
return i
x = 16
print (firstFactorialDivisibleNumber(x))
|
C#
using System;
class GFG {
static int firstFactorialDivisibleNumber( int x)
{
int i = 1;
int fact = 1;
for (i = 1; i < x; i++) {
fact = fact * i;
if (fact % x == 0)
break ;
}
return i;
}
public static void Main()
{
int x = 16;
Console.Write(
firstFactorialDivisibleNumber(x));
}
}
|
PHP
<?php
function firstFactorialDivisibleNumber( $x )
{
$i = 1;
$fact = 1;
for ( $i = 1; $i < $x ; $i ++)
{
$fact = $fact * $i ;
if ( $fact % $x == 0)
break ;
}
return $i ;
}
$x = 16;
echo (firstFactorialDivisibleNumber( $x ));
?>
|
Javascript
<script>
function firstFactorialDivisibleNumber(x)
{
var i = 1;
var fact = 1;
for (i = 1; i < x; i++)
{
fact = fact * i;
if (fact % x == 0)
break ;
}
return i;
}
var x = 16;
document.write(firstFactorialDivisibleNumber(x));
</script>
|
If we apply this naive approach, we wouldn’t go above 20! or 21! (long long int will have its upper limit).
A better solution avoids overflow. The solution is based on below observations.
- If i! is divisible by x, then (i+1)!, (i+2)!, … are also divisible by x.
- For a number x, all factorials i! are divisible by x when i >= x.
- If a number x is prime, then no factorial below x can divide it as x cannot be formed with multiplication of smaller numbers.
Below is algorithm
1) Run a loop for i = 1 to n-1
a) Remove common factors
new_x /= gcd(i, new_x);
b) Check if we found first i.
if (new_x == 1)
break;
2) Return i
Below is the implementation of the above idea :
C++
#include <bits/stdc++.h>
using namespace std;
int gcd( int a, int b)
{
if ((a % b) == 0)
return b;
return gcd(b, a % b);
}
int firstFactorialDivisibleNumber( int x)
{
int i = 1;
int new_x = x;
for (i = 1; i < x; i++) {
new_x /= gcd(i, new_x);
if (new_x == 1)
break ;
}
return i;
}
int main( void )
{
int x = 16;
cout << firstFactorialDivisibleNumber(x);
return 0;
}
|
Java
class GFG {
static int gcd( int a, int b)
{
if ((a % b) == 0 )
return b;
return gcd(b, a % b);
}
static int firstFactorialDivisibleNumber( int x)
{
int i = 1 ;
int new_x = x;
for (i = 1 ; i < x; i++) {
new_x /= gcd(i, new_x);
if (new_x == 1 )
break ;
}
return i;
}
public static void main(String[] args)
{
int x = 16 ;
System.out.print(firstFactorialDivisibleNumber(x));
}
}
|
Python3
def gcd(a, b):
if ((a % b) = = 0 ):
return b
return gcd(b, a % b)
def firstFactorialDivisibleNumber(x):
i = 1
new_x = x
for i in range ( 1 ,x):
new_x / = gcd(i, new_x)
if (new_x = = 1 ):
break
return i
def main():
x = 16
print (firstFactorialDivisibleNumber(x))
if __name__ = = '__main__' :
main()
|
C#
using System;
class GFG {
static int gcd( int a, int b)
{
if ((a % b) == 0)
return b;
return gcd(b, a % b);
}
static int firstFactorialDivisibleNumber(
int x)
{
int i = 1;
int new_x = x;
for (i = 1; i < x; i++) {
new_x /= gcd(i, new_x);
if (new_x == 1)
break ;
}
return i;
}
public static void Main()
{
int x = 16;
Console.Write(
firstFactorialDivisibleNumber(x));
}
}
|
PHP
<?php
function gcd( $a , $b )
{
if (( $a % $b ) == 0)
return $b ;
return gcd( $b , $a % $b );
}
function firstFactorialDivisibleNumber( $x )
{
$i = 1;
$new_x = $x ;
for ( $i = 1; $i < $x ; $i ++)
{
$new_x /= gcd( $i , $new_x );
if ( $new_x == 1)
break ;
}
return $i ;
}
$x = 16;
echo (firstFactorialDivisibleNumber( $x ));
?>
|
Javascript
<script>
function gcd(a, b)
{
if ((a % b) == 0)
return b;
return gcd(b, a % b);
}
function firstFactorialDivisibleNumber(x)
{
let i = 1;
let new_x = x;
for (i = 1; i < x; i++)
{
new_x = parseInt(new_x / gcd(i, new_x), 10);
if (new_x == 1)
break ;
}
return i;
}
let x = 16;
document.write(firstFactorialDivisibleNumber(x));
</script>
|
Another approach using boost library:
(Thanking ajay0007 for contributing this approach)
Here we use boost library to efficiently calculate the value of factorial.
Prerequisite :boost-multiprecision-library
C++
#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>
using boost::multiprecision::cpp_int;
using namespace std;
cpp_int fact( int n)
{
cpp_int num = 1;
for ( int i = 1; i <= n; i++)
num = num * i;
return num;
}
int Special_Factorial_Number( int k)
{
for ( int i = 1 ; i <= k ; i++ )
{
if ( ( fact (i) % k ) == 0 )
{
return i;
}
}
}
int main()
{
int k = 16;
cout<<Special_Factorial_Number(k);
}
|
Java
public class GFG {
static int fact( int n) {
int num = 1 ;
for ( int i = 1 ; i <= n; i++) {
num = num * i;
}
return num;
}
static int Special_Factorial_Number( int k) {
for ( int i = 1 ; i <= k; i++) {
if (fact(i) % k == 0 ) {
return i;
}
}
return 0 ;
}
public static void main(String[] args) {
int k = 16 ;
System.out.println(Special_Factorial_Number(k));
}
}
|
Python3
def fact( n):
num = 1
for i in range ( 1 , n + 1 ):
num = num * i
return num
def Special_Factorial_Number(k):
for i in range ( 1 , k + 1 ):
if (fact(i) % k = = 0 ):
return i
return 0
if __name__ = = '__main__' :
k = 16
print (Special_Factorial_Number(k))
|
C#
using System;
public class GFG{
static int fact( int n) {
int num = 1;
for ( int i = 1; i <= n; i++) {
num = num * i;
}
return num;
}
static int Special_Factorial_Number( int k) {
for ( int i = 1; i <= k; i++) {
if (fact(i) % k == 0) {
return i;
}
}
return 0;
}
public static void Main() {
int k = 16;
Console.WriteLine(Special_Factorial_Number(k));
}
}
|
PHP
<?php
function fact( $n )
{
$num = 1;
for ( $i = 1; $i <= $n ; $i ++)
$num = $num * $i ;
return $num ;
}
function Special_Factorial_Number( $k )
{
for ( $i = 1 ; $i <= $k ; $i ++ )
{
if (( fact ( $i ) % $k ) == 0 )
{
return $i ;
}
}
}
$k = 16;
echo Special_Factorial_Number( $k );
?>
|
Javascript
<script>
function fact(n) {
let num = 1;
for (let i = 1; i <= n; i++) {
num = num * i;
}
return num;
}
function Special_Factorial_Number(k) {
for (let i = 1; i <= k; i++) {
if (fact(i) % k == 0) {
return i;
}
}
return 0;
}
let k = 16;
document.write(Special_Factorial_Number(k));
</script>
|
Output :
6
Time complexity: O(n^2) since using a for loop in another for loop
Auxiliary Space: O(1) because it is using constant variable
Method 4: Using a generator
This code uses generators and loops to find the first natural number whose factorial is divisible by a given number x.
The factorial_gen() function is a generator that yields the factorial of each natural number starting from 1. It uses a while loop that keeps multiplying the current factorial with the next natural number and yields the result at each iteration.
The factorial_divisible_by_x() function takes the input x and loops through the factorials generated by factorial_gen(). It checks if the current factorial is divisible by x using the modulo operator. If it is, then the function returns the index of the natural number (i+1) whose factorial was found to be divisible by x.
Finally, the code calls the factorial_divisible_by_x() function with x = 10 and prints the result.
C++
#include <iostream>
using namespace std;
int main()
{
int fact = 1;
int i = 1;
int x = 10;
int count = 0;
while ( true ) {
if (fact % x == 0) {
count = i;
break ;
}
i++;
fact *= i;
}
cout << count << endl;
return 0;
}
|
Java
public class Main {
public static void main(String[] args)
{
int fact = 1 ;
int i = 1 ;
int x = 10 ;
int count = 0 ;
while ( true ) {
if (fact % x == 0 ) {
count = i;
break ;
}
i++;
fact *= i;
}
System.out.println(count);
}
}
|
Python3
def factorial_gen():
fact = 1
i = 1
while True :
yield fact
i + = 1
fact * = i
def factorial_divisible_by_x(x):
for i, f in enumerate (factorial_gen()):
if f % x = = 0 :
return i + 1
x = 10
print (factorial_divisible_by_x(x))
|
Javascript
let x = 10;
let fact = 1;
let i = 1;
let count = 0;
while ( true ) {
if (fact % x === 0) {
count = i;
break ;
}
i++;
fact *= i;
}
console.log(count);
|
C#
using System;
class Program {
static void Main( string [] args) {
int fact = 1;
int i = 1;
int x = 10;
int count = 0;
while ( true ) {
if (fact % x == 0) {
count = i;
break ;
}
i++;
fact *= i;
}
Console.WriteLine(count);
}
}
|
The time complexity of the factorial_divisible_by_x function depends on the value of x and the number of iterations it takes to find the first factorial that is divisible by x. The factorial_gen generator function has a time complexity of O(n) as it generates factorials endlessly.
The space complexity of both functions is O(1) as they only use a fixed number of variables to store the factorial and the index. The factorial_gen generator does not store all the factorials it generates at once, but only the latest one.
This article is contributed by Shubham Gupta. If you like neveropen and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the neveropen main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!