形如该题:用到了循环节
1
2 4 8 6
3 9 7 1
4 6
5
6
7 9 3 1
8 4 2 6
9 1
如图为一到十的数字乘方的个位数的循环,可以看出有的数1个数一循环,有的是2个数一循环,有的是4个一循环。
例题:
则4肯定是所有所有个位数n次方的个位的循环节,因为4是1的倍数也是2的倍数也是四的倍数
如图p的数太大,只能用字符串保存。由于循环节为4可知只需要取p的最后两位即可。因为两位数的范围为0~100肯定包含了循环节的数,除非p.size<2则直接取p即可,亦或者p形如10000后两位为00,则只需要在取数时加4即可。
此为核心的代码。快速幂的实现可参考快速幂和龟速乘-CSDN博客。
int x;
string y;
cin >> x >> y;
int circle;
if (y.size() >= 2)
circle = stoi(y.substr(y.size() - 2, 2)) + 4;
//stoi意为string转为int
//substr意为y的下标为y.size-2的位置开始取2个元素组成的字符串
else
circle = stoi(y);
int real = x % 10;
cout<< quickpower(real, circle)<<endl;//快速幂
全部代码实现为
#include<bits/stdc++.h>
using namespace std;
int quickpower(int x, int y)
{
int ret = 0;
if (y == 0)
return 1;
int atp = quickpower(x, y / 2) % 10;
if (y % 2)
ret = atp * atp * x;
else
ret = atp * atp;
return ret % 10;
}
int main()
{
int t;cin >> t;
while (t--)
{
int x;
string y;
cin >> x >> y;
int circle;
if (y.size() >= 2)
circle = stoi(y.substr(y.size() - 2, 2)) + 4;
else
circle = stoi(y);
int real = x % 10;
cout<< quickpower(real, circle)<<endl;
}
return 0;
}