HDOJ A hard puzzle

A hard puzzle
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 37440 Accepted Submission(s): 13415


Problem Description
lcy gives a hard puzzle to feng5166,lwg,JGShining and Ignatius: gave a and b,how to know the a^b.everybody objects to this BT problem,so lcy makes the problem easier than begin.
this puzzle describes that: gave a and b,how to know the a^b's the last digit number.But everybody is too lazy to slove this problem,so they remit to you who is wise.



Input
There are mutiple test cases. Each test cases consists of two numbers a and b(0<a,b<=2^30)



Output
For each test case, you should output the a^b's last digit number.



Sample Input
7 66
8 800


Sample Output
9

6


这一题一次提交通过, 算最后一位的话,a输入就得a=a%10取最后一位来算,此后结果也只保留最后一位来计算,即ans=ans*a%10;但是我想b那么那大直接枚举应该会超时,但是在计算过程中会出之前出现过的答案,所以应该找出周期再经行计算。


# include <stdio.h>
int temp[10000];//保存之前出现过的结果
int main(){
	int ans, a, b, cur, i, j, k, flage, cycle;
	while(scanf("%d%d", &a, &b)!=EOF){
		a=a%10;
		ans=1;
		cur=0;
		flage=0;//是否找到周期的标志
		temp[cur++]=ans;
		for(i=1; i<=b; i++){
			ans=ans*a%10;
			temp[cur++]=ans;
			for(j=0; j<=i-1; j++){
				if(temp[j]==ans){
					flage=1;
					cycle=i-j;//计算周期
					break;
				}
			}
			if(flage){//找到周期
				break;
			}
		}
		if(!flage){//未找到周期
			printf("%d\n", ans);
		}
		else{
			b=(b-i)%cycle;
			for(j=1; j<=b; j++){
				ans=ans*a%10;
			}
			printf("%d\n", ans);
		}
	}
	return 0;
}


你可能感兴趣的:(枚举,循环,周期性,乘方,模运算)