A factorial number
F
is any natural number for
n
>
0
such that
F
=
n
!
. So the first few factorial numbers are
1
,
2
,
6
,
2
4
,
1
2
0
,
7
2
0
.
.
.
.
.
.
. Implement an algorithm that takes two parameters
(low, high)
and returns the count of the factorial number in that range. How many factorial numbers are there between
1
0
1
3
and
1
0
1
0
0
0
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
I'm still a beginner in programming so there are probably shorter solutions but here is my code in Python 2.7:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Line 6 starts with x = 0 , and adds 1 until x! > low. When the value of x! is between low and high, the counter counts how many values of x satisfy the condition while incrementing x. And when x!>high, the count is printed.
That's a good solution for a beginner! It's great that you explained why your code works :)
A better and efficient way to do this is to make use of logarithms. We know that f ( x ) = lo g 1 0 x and g ( x ) = 1 0 x are strictly increasing functions ∀ x ∈ ( 0 , ∞ ) , so we can apply logarithm of base 1 0 to all sides of an inequality and the inequality direction remains preserved. Similarly, we can apply exponential of base 1 0 to all sides of an inequality and the inequality direction remains preserved. So, we have,
low < n ! < high ⟺ lo g 1 0 ( low ) < lo g 1 0 ( n ! ) = k = 1 ∑ n lo g 1 0 k < lo g 1 0 ( high )
So, we can use the latter equivalent condition to implement an algorithm to get the count of the factorials between
low
and
high
. The advantage of this method is that it's computationally more efficient since it avoids computing large values of factorials. Also, this algorithm is portable to other languages which do not support such big value storing native datatype (for example, C++).
Here
's a C++ code using this algorithm. I can't take the
low
and
high
as parameters since there's no native C++ datatype to store such large parameters. Instead I
#define
d the base
1
0
logarithms of
low
and
high
as
LOW_LOG_10
and
HIGH_LOG_10
for this problem at the beginning manually. To change the parameters, you'll need to manually fork the code and change the values of
LOW_LOG_10
and
HIGH_LOG_10
by redefining them accordingly.
Problem Loading...
Note Loading...
Set Loading...