hdu1097 A hard puzzle

本文介绍了一种快速计算a^b末位数字的方法,并提供了两种实现思路的C++代码示例。通过观察数字循环规律并利用数组存储,或者简化运算过程来提高效率。

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^b最后一位的,可以求出0~9循环多少次又回到原来的值,比如2的次方是2 4 8 16 32 周期是4
然后把这些数存起来就是数组
int c[10][5]={
              {0},{1},{2,4,8,6},{3,9,7,1},{4,6},{5},
              {6},{7,9,3,1},{8,4,2,6},{9,1}     
             };

#include<iostream>
#include<cmath>
using namespace std;
const
int c[10][5]={
              {0},{1},{2,4,8,6},{3,9,7,1},{4,6},{5},
              {6},{7,9,3,1},{8,4,2,6},{9,1}     
             };
int main()
{
    int a,b;
    int sum,i,k;
    while(cin>>a>>b)
    {    
     k=1;
     if(a>=10)
     a=a%10;
     sum=a;
     for(i=1;i<=k;i++)//最多循环5次 
     {
      sum*=a;
      if(sum>=10)
      {
       sum%=10;                  
      }
      if(sum!=a)
      {k=k+1;}
     }     
     if(b%(i-1)==0) cout<<c[a][b%(i-1)+(i-1)-1]<<endl;//注意输出,原来我没有
      else cout<<c[a][b%(i-1)-1]<<endl;  
    }
    return 0;
}



另一种:

#include <iostream>
using namespace std;
int main()
{
	int a, b, n;
	while (cin>>a>>b) {
		a %= 10;
		b %= 4;
		switch(b) {
		case 1:
			n = a%10;
			break;
		case 2:
			n = a*a%10;
			break;
		case 3:
			n = a*a*a%10;
			break;
		case 0:
			n = a*a*a*a%10;
			break;
		default:
			break;
		}
		cout<<n<<endl;
	}
	return 0;
}


害羞

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值