使用 C++ 查找 N 个阶乘之和的个位数。


在这里,我们将了解如何获取 N 个阶乘之和的个位数。所以如果 N 是 3,那么在得到和之后,我们将得到 1! + 2! + 3! = 9,这将是结果,对于 N = 4,它将是 1! + 2! + 3! + 4! = 33。所以个位数是 3。如果我们仔细观察,那么当 N > 5 时,阶乘的个位数为 0,所以 5 之后,它将不会导致个位数发生变化。对于 N = 4 及以上,它将是 3。我们可以为个位数制作一个图表,这将在程序中使用。

示例

#include<iostream>
#include<cmath>
using namespace std;
double getUnitPlace(int n) {
   int placeVal[5] = {-1, 1, 3, 9, 3};
   if(n > 4){
      n = 4;
   }
   return placeVal[n];
}
int main() {
   for(int i = 1; i<10; i++){
      cout << "Unit place value of sum of factorials when N = "<<i<<" is: " << getUnitPlace(i) << endl;
   }
}

输出

Unit place value of sum of factorials when N = 1 is: 1
Unit place value of sum of factorials when N = 2 is: 3
Unit place value of sum of factorials when N = 3 is: 9
Unit place value of sum of factorials when N = 4 is: 3
Unit place value of sum of factorials when N = 5 is: 3
Unit place value of sum of factorials when N = 6 is: 3
Unit place value of sum of factorials when N = 7 is: 3
Unit place value of sum of factorials when N = 8 is: 3
Unit place value of sum of factorials when N = 9 is: 3

更新于: 2019 年 10 月 30 日

139 次查看

开启你的 职业生涯

完成课程获得认证

开始学习
广告