如果存在一些整数I> = 0,使得F = I,则数字F是阶乘数。 (也就是说,F是I的阶乘)。阶乘数的示例是1、2、6、24、120等。
编写一个程序,将两个长整数’low’和’high’作为输入,其中0
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)找到大于或等于低的第一个阶乘。让这个阶乘为x! (x的阶乘)和该阶乘的值是“事实”
2)不断增加x,并在事实小于或等于high时继续更新“事实”。计算该循环运行的次数。
3)返回在步骤2中计算的计数。
下面是上述算法的实现。感谢Kartik提供以下解决方案的建议。
C++
// Program to count factorial numbers in given range
#include
using namespace std;
int countFact(int low, int high)
{
// Find the first factorial number 'fact' greater than or
// equal to 'low'
int fact = 1, x = 1;
while (fact < low)
{
fact = fact*x;
x++;
}
// Count factorial numbers in range [low, high]
int res = 0;
while (fact <= high)
{
res++;
fact = fact*x;
x++;
}
// Return the count
return res;
}
// Driver program to test above function
int main()
{
cout << "Count is " << countFact(2, 720);
return 0;
}
Java
// Java Program to count factorial
// numbers in given range
class GFG
{
static int countFact(int low, int high)
{
// Find the first factorial number
// 'fact' greater than or equal to 'low'
int fact = 1, x = 1;
while (fact < low)
{
fact = fact * x;
x++;
}
// Count factorial numbers
// in range [low, high]
int res = 0;
while (fact <= high)
{
res++;
fact = fact * x;
x++;
}
// Return the count
return res;
}
// Driver code
public static void main (String[] args)
{
System.out.print("Count is "
+ countFact(2, 720));
}
}
// This code is contributed by Anant Agarwal.
Python3
# Program to count factorial
# numbers in given range
def countFact(low,high):
# Find the first factorial number
# 'fact' greater than or
# equal to 'low'
fact = 1
x = 1
while (fact < low):
fact = fact * x
x += 1
# Count factorial numbers
# in range [low, high]
res = 0
while (fact <= high):
res += 1
fact = fact * x
x += 1
# Return the count
return res
# Driver code
print("Count is ", countFact(2, 720))
# This code is contributed
# by Anant Agarwal.
C#
// C# Program to count factorial
// numbers in given range
using System;
public class GFG
{
// Function to count factorial
static int countFact(int low, int high)
{
// Find the first factorial number numbers
// 'fact' greater than or equal to 'low'
int fact = 1, x = 1;
while (fact < low)
{
fact = fact * x;
x++;
}
// Count factorial numbers
// in range [low, high]
int res = 0;
while (fact <= high)
{
res++;
fact = fact * x;
x++;
}
// Return the count
return res;
}
// Driver code
public static void Main ()
{
Console.Write("Count is " + countFact(2, 720));
}
}
// This code is contributed by Sam007
PHP
Javascript
输出 :
Count is 5