zoukankan      html  css  js  c++  java
  • 快速幂模板

    (b^p)%k
    递归版 :

    #include<iostream>
    #include<cstdio>
    #define ll long long
    using namespace std;
    inline void read(ll &x){
    	int f=1;
    	x=0;
    	char ch=getchar();
    	while(ch<'0'||ch>'9'){
    		if(ch=='-') f=-1;
    		ch=getchar();
     	}
     	while(ch>='0'&&ch<='9'){
     		x=x*10+ch-'0';
     		ch=getchar();
    	}
    	x*=f; 
    }
    inline ll quick_pow(ll b,ll p,ll k){
            if(p==0) return 1;
    	if(p==1) return b; 
    	ll res=quick_pow(b,p>>1,k);
    	res=res%k*res%k;
    	if(p%2==1) res=res%k*b%k;
    	return res%k;
    }
    int main(){
    	ll a,b,c;
    	read(a);read(b);read(c);
    	printf("%lld^%lld mod %lld=",a,b,c);
    	printf("%lld",quick_pow(a,b,c)%c);
    	return 0;
    } 
    

    非递归版 :

    #include<iostream>
    #include<cstdio>
    #define ll long long
    using namespace std;
    inline void read(ll &x){
    	int f=1;
    	x=0;
    	char ch=getchar();
    	while(ch<'0'||ch>'9'){
    		if(ch=='-') f=-1;
    		ch=getchar();
     	}
     	while(ch>='0'&&ch<='9'){
     		x=x*10+ch-'0';
     		ch=getchar();
    	}
    	x*=f; 
    }
    inline ll quick_power(ll b,ll p,ll k){
    	ll ans=1;	//结果 
    	while(p>0){
    		if(p&1) ans=ans*b%k;	//p&1 == p%2==1
    		b=b*b%k;
    		p>>=1;	 //p>>=1 == p/2;
    	}
    	return ans;
    }
    int main(){
    	ll a,b,c;
    	read(a);read(b);read(c);
    	printf("%lld",quick_power(a,b,c)%c);      //输出时必须%c,要不然会报错
    	return 0;
    } 
    
  • 相关阅读:
    8皇后问题
    求1到n,n个整数的全排列
    求最小周期串
    如何用java完成一个中文词频统计程序
    蛇形矩阵
    第一个算法程序
    java 继承练习题8
    java 继承练习题7
    java 继承练习题6
    java 继承练习题5
  • 原文地址:https://www.cnblogs.com/-pwl/p/13693077.html
Copyright © 2011-2022 走看看