每日一算法 A^B Problem

http://acm.nyist.net/JudgeOnline/problem.php?pid=473


描述
Give you two numbers a and b,how to know the a^b's the last digit number.It looks so easy,but everybody is too lazy to slove this problem,so they remit to you who is wise.
输入
There are mutiple test cases. Each test cases consists of two numbers a and b(0<=a,b<2^30)
输出
For each test case, you should output the a^b's last digit number.
样例输入
7 66
8 800
样例输出
9
6
提示
There is no such case in which a = 0 && b = 0。



简述之,就是求a^b的最低位。


思路:既然是求最低位,那么肯定就只与a的最低位有关了

  a %= 10;   /*取a的最低位*/

求一个数的N次方那么它的尾数会不会有规律呢,我们来试试


对于a的尾数(b不为0)

为0时,a^b的尾数为0....

为1时,a^b尾数为 1;

为2时,a^b尾数为2,4,8,6,  2,4,8,6.....

为3时,a^b的尾数为3,9,7,1, 3,9,7,1....

为4时,a^b的尾数为4,6,4,6, 4,6,4,6,4....

为5时,a^b的尾数为5,5,5,5, 5,5....

为6时,a^b的尾数为6,6,6,6, 6,6,6....

为7时,a^b的尾数为7,9,3,1, 7,9,3.1....

为8时,a^b的尾数为8,4,2,6, 8,4,2,6....

为9时,a^b的尾数为9,1,9,1,9, 1,9,1,9....


为了统一,我们都可以看作是4次一个循环。


#include <stdio.h>
int main()
{
  int a,b;
  int i,s;
  while(scanf("%d%d",&a,&b)!=EOF)
  {
    if(b==0)
      printf("1\n");
    else 
    {
      a%=10;
      b=b%4+4;
      s=a;
      for(i=1;i<b;i++)
      s*=a; //模拟a^b,简化程序的运行
      s%=10;//获取尾数
      printf("%d\n",s);
    }
  }
return 0;
}



ACM答案

 
#include <stdio.h>

int ac[10][4]={{0,0,0,0},{1,1,1,1},{6,2,4,8},{1,3,9,7},{6,4,6,4},{5,5,5,5},{6,6,6,6},{1,7,9,3},{6,8,4,2},{1,9,1,9}};

int main()
{
    int a,b;
    while(~scanf("%d%d",&a,&b))
        printf("%d\n",b?ac[a%10][b%4]:1);
    return 0;
}
        

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值