A number F is a factorial number if there exists some integer I >= 0 such that F = I! (that is, F is factorial of I). Examples of factorial numbers are 1, 2, 6, 24, 120, ….
Write a program that takes as input two long integers ‘low’ and ‘high’ where 0 < low < high and finds count of factorial numbers in the closed interval [low, high].
Examples :
Input: 0 1
Output: 1 //Reason: Only factorial number is 1
Input: 12 122
Output: 2 // Reason: factorial numbers are 24, 120
Input: 2 720
Output: 5 // Factorial numbers are: 2, 6, 24, 120, 720
1) Find the first factorial that is greater than or equal to low. Let this factorial be x! (factorial of x) and value of this factorial be ‘fact’
2) Keep incrementing x, and keep updating ‘fact’ while fact is smaller than or equal to high. Count the number of times, this loop runs.
3) Return the count computed in step 2.
Below is implementation of above algorithm. Thanks to Kartik for suggesting below solution.
C++
#include <iostream>
using namespace std;
int countFact( int low, int high)
{
int fact = 1, x = 1;
while (fact < low)
{
fact = fact*x;
x++;
}
int res = 0;
while (fact <= high)
{
res++;
fact = fact*x;
x++;
}
return res;
}
int main()
{
cout << "Count is " << countFact(2, 720);
return 0;
}
|
Java
class GFG
{
static int countFact( int low, int high)
{
int fact = 1 , x = 1 ;
while (fact < low)
{
fact = fact * x;
x++;
}
int res = 0 ;
while (fact <= high)
{
res++;
fact = fact * x;
x++;
}
return res;
}
public static void main (String[] args)
{
System.out.print( "Count is "
+ countFact( 2 , 720 ));
}
}
|
Python3
def countFact(low,high):
fact = 1
x = 1
while (fact < low):
fact = fact * x
x + = 1
res = 0
while (fact < = high):
res + = 1
fact = fact * x
x + = 1
return res
print ( "Count is " , countFact( 2 , 720 ))
|
C#
using System;
public class GFG
{
static int countFact( int low, int high)
{
int fact = 1, x = 1;
while (fact < low)
{
fact = fact * x;
x++;
}
int res = 0;
while (fact <= high)
{
res++;
fact = fact * x;
x++;
}
return res;
}
public static void Main ()
{
Console.Write( "Count is " + countFact(2, 720));
}
}
|
PHP
<?php
function countFact( $low , $high )
{
$fact = 1; $x = 1;
while ( $fact < $low )
{
$fact = $fact * $x ;
$x ++;
}
$res = 0;
while ( $fact <= $high )
{
$res ++;
$fact = $fact * $x ;
$x ++;
}
return $res ;
}
echo "Count is " , countFact(2, 720);
?>
|
Javascript
<script>
function countFact(low, high)
{
let fact = 1;
let x = 1;
while (fact < low)
{
fact = fact * x;
x++;
}
let res = 0;
while (fact <= high)
{
res++;
fact = fact * x;
x++;
}
return res;
}
document.write( "Count is " + countFact(2, 720));
</script>
|
Output :
Count is 5
Time complexity: approximately equal to O(K) where K is the biggest divisor of high and is not equal to high.
Auxiliary space complexity: O(1).
This article is contributed by Shivam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.