1. 程式人生 > >hdu1097A hard puzzle(快速冪演算法)

hdu1097A hard puzzle(快速冪演算法)

A hard puzzle


題目:

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)%q = a%q*b%q

快速冪演算法:(學習:https://blog.csdn.net/Hacker_ZhiDian/article/details/79153131

#include <iostream>
#include <algorithm>
 
using namespace std;
int PowerMod(long long a, long long b, int n)
{
	int ans=1;
	a=a%n;
	while(b>0)
	{
		if(b%2==1)
			ans=(ans*a)%n;
		b/=2;
		a=(a*a)%n;
	};
	return ans;
}

//
//  main.cpp
//  hdu1097
//
//  Created by zhan_even on 2018/10/31.
//  Copyright © 2018年 zhan_even. All rights reserved.
//

#include <iostream>
#include <algorithm>
using namespace std;


int PowerMod(int a, int b, int n)
{
    int ans=1;
    a=a%n;
    while(b>0)
    {
        if(b%2==1)
            ans=(ans*a)%n;
        b/=2;
        a=(a*a)%n;
    };
    return ans;
}
int main(int argc, const char * argv[]) {
    int a,b;
    while (cin>>a>>b) {
        cout<<PowerMod(a, b, 10)<<endl;
    }
    return 0;
}