模板--快速幂运算||快速乘运算

快速幂运算模板:

(1)时间复杂度:O(log(n));非递归调用;

typedef long long ll;

ll mod_pow(ll x,ll n,ll mod){
    ll res=1;
	while(n>0){
		if(1&n)	res=res*x%mod;
		x=x*x%mod;
		n=n>>1;
	} 
	return res;
}

(2)时间复杂度:O(log(n));递归调用;

typedef long long ll;

ll mod_pow(ll x,ll n,ll mod){
    if(n==1)	return 1;
    ll res=mod_pow(x*x%mod,n/2,mod);
    if(n&1)	res=res*x%mod;
	return res;
}

(3)快速乘运算:

LL mul_mod(LL a,LL b,LL mod){
    LL ret=0;
    while(b){
        if(b&1)    ret=ret+a;
        if(ret>=mod)	ret-=mod;
        a=a+a;
        if(a>=mod)	a-=mod;
        b>>=1;
    }
    return ret;
}

(4)快速乘运算+快速幂运算:

LL mul_mod(LL a,LL b,LL mod){
    LL ret=0;
    while(b){
        if(b&1)    ret=ret+a;
        if(ret>=mod)	ret-=mod;
        a=a+a;
        if(a>=mod)	a-=mod;
        b>>=1;
    }
    return ret;
}
LL pow_mod(LL a,LL b,LL mod){
    LL ret=1;
    while(b){
        if(b&1)ret=mul_mod(ret,a,mod);
        a=mul_mod(a,a,mod);
        b>>=1;
    }
    return ret;
}

猜你喜欢

转载自blog.csdn.net/queque_heiya/article/details/105929064