C++ 中阶乘的位数统计


给定一个整数,任务是首先计算该数的阶乘,然后计算结果中的总位数。

什么是阶乘数

一个数的阶乘是通过将该数的数字相乘,同时将数字的值递减 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 − factorial(6)
Output − number of digits in factorial(6) is: 3

说明 - 由于 6 的阶乘值为 720,它包含 3 位数字,因此结果为 3

Input − factorial(12)
Output− number of digits in factorial(12) is: 9

说明 - 由于 12 的阶乘值为 479001600,它包含 9 位数字,因此结果为 9。

下面程序中使用的解决方法如下

  • 输入需要计算阶乘的数字。

  • 如果数字小于 0,则返回 0,因为负数没有阶乘值。

  • 如果数字为 1,则返回 1,因为 1!为 1 且它有 1 位数字。

  • 如果数字大于 1,即从 2 或更大开始,则创建一个循环,从 2 开始,直到它小于或等于数字。

  • 取一个临时变量,比如 d,在循环外将其初始化为 0,并在循环内不断地将其加上 log10(i) 的值,直到 i 的每次迭代。

  • 之后,返回“floor(d)+1”的向下取整值。

  • 打印结果。

示例

 在线演示

#include <iostream>
#include <cmath>
using namespace std;
// This function returns the number of digits present in num!
int count_digits(int num){
   // factorial exists only if num <= 0
   if (num < 0){
      return 0;
   }
   // base case
   if (num <= 1){
      return 1;
   }
   // else iterate through num and calculate the
   // value
   double d = 0;
   for (int i=2; i<=num; i++){
      d += log10(i);
   }
   return floor(d) + 1;
}
int main(){
   cout<<"number of digits in factorial(1) is: "<<count_digits(1)<< endl;
   cout<<"number of digits in factorial(6) is: "<<count_digits(6) << endl;
   cout<<"number of digits in factorial(106) is: "<<count_digits(106) << endl;
   return 0;
}

输出

如果我们运行以上代码,它将生成以下输出:

number of digits in factorial(1) is: 1
number of digits in factorial(6) is: 3
number of digits in factorial(106) is: 171

更新于: 2020 年 5 月 15 日

2K+ 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.