数学—快速幂

时间:2021-05-04 13:59:59   收藏:0   阅读:14

快速幂

原理:

快速幂

模块化

#include<iostream>
#include<stdio.h>
using namespace std;
#define ll long long
int qmi(int a,int k,int p)
{
	ll res=1;
	while(k)
	{
		if(k&1)res=(ll)res*a%p;
		k=k>>1;
		a=(ll)a*a%p;
	}
	return res;
}
int main()
{
	int n;
	cin>>n;
	while(n--)
	{
		ll a,k,p;
		cin>>a>>k>>p;
		cout<<qmi(a,k,p)<<endl; 
	}
	return 0;
}

原晨旭

#include<iostream>
#include<stdio.h>
using namespace std;
#define ll long long
int main()
{
	int n;
	cin>>n;
	while(n--)
	{
		ll a,k,p;
		cin>>a>>k>>p;
		ll res=1;
		//将幂转化为二进制,对每一位都进行判定 
		while(k>0)
		{
			if(k&1)res=(ll)res*a%p;
			k=k>>1;
			a=(ll)a*a%p; 
		}
		cout<<res<<endl; 
	}
	return 0;
}

原文:https://www.cnblogs.com/BeautifulWater/p/14729169.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!