题面:
![](https://img-blog.csdnimg.cn/img_convert/a5e1610141f14cd89f4df96d5536ab0f.png)
解题:
long long?高精?储存50,000,000!? NO!NO!NO!
如此的空间复杂度、时间复杂度都不太能扛得住。
排除了暴力做法,结合题目来分析:
假如两个数相乘后不产生0,那么乘积的个位即所求第一个非零元素,
因此,每次相乘后,我们只需要对结果保留个位即可,即%10,因此不用担心数据溢出;
0产生的原因
一方面有例如10、200、3000这样整十整百的数,而末尾的0对非零位没有影响,我们需要把其末尾0全部删掉,取非零位的第一个元素即可;
另一方面,5×2也能得到0,不妨把所有乘数中的2、5全部提取出来,
而2的产生速率远远大于5,因此,在最后,我们将所有5与2配对,再将答案乘上剩下的2即可
AC代码奉上
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
long long n, fiveIndex = 0, twoIndex = 0, ans = 1;
int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
{
int temp = i;
while (temp % 10 == 0)temp /= 10; //末尾的0不参与乘法运算
while (temp % 5 == 0) //记录5的个数
{
temp /= 5;
fiveIndex++;
}
while (temp % 2 == 0) //记录2的个数
{
temp /= 2;
twoIndex++;
}
ans *= temp;
ans %= 10;//自信保留个位即可
}
int round = (twoIndex - fiveIndex) % 4;
int condition[4] = { 6,2,4,8 }; //乘1,2,3,4次2位数分别为2/4/8/6
ans *= condition[round];
cout << ans % 10 << endl;
return 0;
}