第五次测试 A的B次方 快速幂算法

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
lcy给风5166,lwg,JGShining和Ignatius出了一个难题:给出了a和b,如何知道a^ b。每个人都反对这个BT问题,所以lcy使问题比开始容易。这个谜题描述的是:给定a和b。如何知道一个a^ b的最后一位数字。但是每个人都懒得解决这个问题,所以他们把问题交给你。
输入*

    • *有多个测试用例。每个测试用例由a和b两个数字(0 < a、b < = 2 ^ 30)
    • *输出
  • 对于每个测试用例,您应该输出一个^ b的最后一位数。
  • 作为一个小萌新刚看到这道题的时候并不知道这类题的模板,于是花费大量时间找规律写代码,但是测试结束后大佬说这道题是考查快速幂的,emmmmm一脸懵逼,快速幂是啥?
  • 随便搜索一下就能找到关于快速幂的各种博客,具体的进行推论交给大佬去写吧。
#include<stdio.h>
int ksm(int a,int b );
int main ()
{
   int a,b;
   int ans;
   while(~scanf("%d%d",&a,&b))
   {		
   	ans=ksm(a,b);
   	printf("%d\n",ans);
   }	
   return 0;
} 
int ksm(int a,int b) 
{
   int ans=1;
   a=a%10;
   while(b>0)
   {
   	if(b%2==1)//可以写成if(b&1)
         {
   	   ans=ans*a%10;	    	
         }
   	a=a*a%10;
   	b=b/2;//可以写成b>>=1;
   }
   return ans;
}

快速幂函数的理解关键就是理解B转化成二进制来运算。

猜你喜欢

转载自blog.csdn.net/weixin_43902655/article/details/84928488