Problem Description
Given a positive integer N, you should output the most right digit of N^N.
Input
The input contains several test cases. The first line of the input is a single integer T which is the number of test cases. T test cases follow.
Each test case contains a single positive integer N(1<=N<=1,000,000,000).
Each test case contains a single positive integer N(1<=N<=1,000,000,000).
Output
For each test case, you should output the rightmost digit of N^N.
Sample Input
2
3
4
Sample Output
7
6
这个题给定的n范围很大,但我们只关心最后一位,于是很容易想到每次都对10取余,但这超时了。其实,对每一个数来说,N^N的个位数是呈周期性的。找出周期所有的问题就解决了。代码如下:
#include<stdio.h> #include<math.h> int a[11]; int main() { int n,k,count,t,i; scanf("%d",&t); while(t--) { count=1; scanf("%d",&n); a[1]=n%10; k=n%10; for(i=2;;i++)//这里不要限定范围(i<=n),因为有可能还没找到周期,循环就已经结束了。 { k*=n%10; k%=10; if(k==a[1]) break; else{ a[++count]=k; } } a[0]=a[count]; printf("%d ",a[(n)%(count)]); } return 0; }