快速幂
快速幂是很快速求幂函数的方法。
用普通方法时间复杂度是O(n),而快速幂的时间复杂度是log(n),但n很大时,时间会明显的得到提升。
下面是模板:
1 ll get_pow(ll x, ll n){ 2 ll ans = 1; 3 while(n){ 4 if(n&1){ 5 ans = x*ans; 6 } 7 x = x*x; 8 n/=2; 9 } 10 return ans; 11 }
不过,但我看到快速幂的推导时,我想到了用递归来做,代码量小,而且更容易理解。
下面是我写的递归模板:
1 ll get_pow(ll x, ll n){ 2 if(n == 1) return x; 3 if(n&1) return x*get_pow(x*x,n/2); 4 else return get_pow(x*x,n/2); 5 }
下面贴一道相关的题目:
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.
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的个位数是多少
1 #include <iostream> 2 #include <cstdio> 3 #define ll long long 4 using namespace std; 5 ll get_pow(int x, int n){ 6 if(n == 1) return x; 7 if(n&1) return x*get_pow((x*x)%10,n/2); 8 else return get_pow((x*x)%10,n/2); 9 } 10 int main(){ 11 ll a, b; 12 while(~scanf("%lld%lld",&a,&b)){ 13 cout << get_pow(a%10,b)%10<<endl; 14 } 15 return 0; 16 }