1. 程式人生 > >【ACM】快速冪(待更)

【ACM】快速冪(待更)

參考網頁:https://www.cnblogs.com/wuyudong/p/3637479.html

https://blog.csdn.net/dbc_121/article/details/77646508 

快速冪依賴於下面的公式!!!

快速冪模板  

int PowerMod(int a, int b, int c)
{
    int ans = 1;
    a = a % c;
    while(b>0) {
        if(b % 2 == 1)
        ans = (ans * a) % c;
        b = b/2;
        a = (a * a) % c;
    }
    return ans;
}

 AC:

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

int main ()
{
	int i,m,T,r;
	cin>>T;
	while(T--)
	{
		cin>>m;
		cout<<PowerMod(m,m,10)<<endl;
	}
	return 0;
}




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

int main ()
{
	int i,m,T,r;
	cin>>T;
	while(T--)
	{
		cin>>m;
		cout<<PowerMod(m,m,10)<<endl;
	}
	return 0;
}