使用 C++ 查找 N 个阶乘之和的最后两位数字。
这里,我们来看如何获取最后两位数字。N 个阶乘之和的个位数和十位数。因此,如果 N = 4,则为 1! + 2! + 3! + 4! = 33。因此,个位数是 3,十位数是 3。结果将是 33。
如果我们清楚地看到,那么当 N > 5 的阶乘时,个位数为 0,因此 5 之后,它不会改变个位数。而且,在 N > 10 之后,十位数将保持为 0。对于 N = 10 及更大值,将变为 00。我们可以绘制一张从 1 到 10 的阶乘数字图表。
我们可以使用以下步骤解决此问题 -
- 如果 n 的值小于 10,则 (1! + 2! + … + n!) mod 10
- 否则,当 n 的值大于或等于 10 时,则 (1! + 2! + … + 10!) mod 10 = 13
示例
#include<iostream> #include<cmath> using namespace std; int getTenAndUnitPlace(long long N) { if (N <= 10) { long long ans = 0, factorial = 1; for (int i = 1; i <= N; i++) { factorial = factorial * i; ans += factorial; } return ans % 100; } return 13; } int main() { for(long long i = 1; i<15; i++){ cout << "Ten and Unit place value of sum of factorials when N = "<<i<<" is: " <<getTenAndUnitPlace(i) << endl; } }
输出
Ten and Unit place value of sum of factorials when N = 1 is: 1 Ten and Unit place value of sum of factorials when N = 2 is: 3 Ten and Unit place value of sum of factorials when N = 3 is: 9 Ten and Unit place value of sum of factorials when N = 4 is: 33 Ten and Unit place value of sum of factorials when N = 5 is: 53 Ten and Unit place value of sum of factorials when N = 6 is: 73 Ten and Unit place value of sum of factorials when N = 7 is: 13 Ten and Unit place value of sum of factorials when N = 8 is: 33 Ten and Unit place value of sum of factorials when N = 9 is: 13 Ten and Unit place value of sum of factorials when N = 10 is: 13 Ten and Unit place value of sum of factorials when N = 11 is: 13 Ten and Unit place value of sum of factorials when N = 12 is: 13 Ten and Unit place value of sum of factorials when N = 13 is: 13 Ten and Unit place value of sum of factorials when N = 14 is: 13
广告