在 C++ 中计算给定范围内阶乘数
给定一个范围,从一个变量(假设为 start)保存的整数值开始,到变量 end 结束,任务是计算给定范围内可用的阶乘数的总数。
什么是阶乘数
一个数的阶乘是通过将该数的数字相乘,同时将数字的值递减 1 来计算的。它用符号“!”表示,例如 0!、1!、2!、3!、5!、……等等。0!和 1!的阶乘始终为 1。
I.e. factorial of 2 = 2 * (2-1) = 2 * 1 = 2 factorial of 3 = 3 * (3-1) * (2-1) = 3 * 2 * 1 = 6
例如
Input − start = 5, end = 600 Output − Count of factorial numbers are 3
解释 - 因为在 5-600 的范围内有 3 个数字具有阶乘数。
Input − start = 1, end = 100 Output − Count of factorial numbers are 5
解释 - 因为在 5-600 的范围内有 5 个数字具有阶乘数。
下面程序中使用的方案如下
输入范围并存储在变量 start 和 end 中
使用另一个变量“fact”来存储阶乘值,并将其初始化为 1,以及一个临时变量“i”来增加数字计数。
启动循环,当 fact 小于 start 时,继续将 fact 与 i 相乘以计算阶乘,并且同时继续增加 i 的值。
启动另一个循环,当 fact 小于等于 end 变量时,继续增加变量 r 的值,并继续将 fact 设置为 fact * i,同时继续增加 i 的值。
现在,返回 r 的值,该值保存着阶乘数的总数。
打印结果。
示例
#include <iostream>
using namespace std;
// To count the number of factorials
int factorials(int start, int end){
// Starting from 1 and find the first factorial number
// 'fact' greater than or equal to 'start'
int fact = 1, i = 1;
while (fact < start){
fact = fact*i;
i++;
}
// r to count factorial numbers in range start to end
int r = 0;
while (fact <= end){
r++;
fact = fact*i;
i++;
}
// Return the count of factorials in range
return r;
}
int main(){
int start = 5, end = 600;
cout << "Count of factorial numbers are " << factorials(start, end);
return 0;
}输出
如果我们运行以上代码,它将生成以下输出:
Count of factorial numbers are 3
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP