【题意】求N^N,输出最右边的那一位。
【代码1:获得周期】
#include <iostream>
#include <iomanip>
#include <cstring>
#include <cstdlib>
#include <cstdio>
using namespace std;
int main()
{
int N = 0;
cin >> N;
while (N--)
{
int mul = 1, n = 0, r = 0, i = 0;
cin >> n;
r = n%10;
for (i = 0; i < n; i++)
{
mul *= r;
mul = mul%10;
}
cout << mul << endl;
}
return 0;
}
【代码2:根据周期输出】
<pre name="code" class="cpp">#include <iostream>
#include <iomanip>
#include <cstring>
#include <cstdlib>
#include <cstdio>
using namespace std;
int main()
{
int N = 0;
int ans[10][4] = {{0,0,0,0},{1,1,1,1},
{2,4,8,6},{3,9,7,1},
{4,6,4,6},{5,5,5,5},
{6,6,6,6},{7,9,3,1},
{8,4,2,6},{9,1,9,1}};
cin >> N;
while (N--)
{
int n = 0, r = 0, l = 0;
cin >> n;
r = n%10;
l = (n-1)%4;
cout << ans[r][l] << endl;
}
return 0;
}
方法二:
来自:http://blog.csdn.net/lovelyloulou/article/details/5241471
这种方法用标志数组去标志周期,但是周期不是1的情况下,如果周期序列中连续出现了两个值相同这种方法就会有bug。但是某一个数连续相乘可能也不会出现这种问题。
#include <iostream>
#include <cstring>
#include <stdio.h>
using namespace std;
bool l[10];
int r[10];
int main()
{
int t;
while(cin>>t)
{
while(t--)
{
memset(l,0,sizeof(l));
memset(r,0,sizeof(r));
int n = 0;
cin>>n;
int a=n%10;
int b=a;
int i=1;
l[b]=true;
r[0]=b;
b=(b*a)%10;
while(!l[b])
{
l[b]=true;
r[i++]=b;
b=(b*a)%10;
}
cout<<r[(n-1)%i]<<endl;
}
}
return 0;
}