题目描述
Given a positive integer N, you should output the most right digit of N^N.
输入
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).
输出
For each test case, you should output the rightmost digit of N^N.
样例输入
2
3
4
样例输出
7
6
题目意思就是,求输入数N的N次方个位上的数。
#include<stdio.h>
int main()
{
int n,a,i,b,c,d;
scanf("%d",&n);
while(n--)
{
scanf("%d",&a);
b=a%10;
c=a%4;
if(c==0)
c=4;
d=1;
for(i=0;i<c;i++)
d*=b;
d%=10;
printf("%d\n",d);
}
}
对于过大的数据,不能一味地用暴力循环的方法解决问题,要么找到更加高效的方法,或者就是寻找是否有周期,有规律可循。
以上的代码是可以通过OJ的,在这之前有一个代码通过不了OJ,输出结果却是和以上的代码一样,待以后学会debug或是请教大神解决。以下是代码
#include<stdio.h>
int main()
{
int i,m,j,n,p,a[5];
scanf("%d",&p);
for(i=1;i<=p;i++)
{
scanf("%d",&n);
a[1]=n%10;
for(m=2;m<=4;m++)
{
//a[m]=(a[m-1]*n%10)%10;
a[m]=(a[m-1]*(n%10))%10;
}
if(n%4==0)
{
printf("%d\n",a[4]);
}
else
{
printf("%d\n",a[n%4]);
}
}
}
以上代码已做修改,可以通过oj,错误处用//标出,如果没有(),计算机会优先计算*,这样就会使数字超出运算范围,有效范围为1000000000,如果带入的数为999999998,在运算时就会运算到999999998*8,超出有效范围,使运算错误,以后写代码还是尽量保持各变量之间的独立性,以防变量在循环中发生改变。