Fast and power modulo operation

The index is converted to binary, 11 th, 11 2 as binary 1011, i.e., 8 + 2 + 1, the self-energizing and specific bits of the base of FIG. 1 or a 0 to add to the base ans. Such time complexity is O (n) = log (2) (n), is very efficient.


1. Source Luo Gu topic: p1226 [template] rapid power modulo operation ||

Codes are as follows:

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

int main()
{
    int a, b;
    scanf("%d%d",&a,&b);
    int base=a,ans=1;//赋初值 
    while(b>0) 
    {
        if(b&1)//按位与0001,只有最右边同为1才执行 
        {
            ans*=base;
        }
        base*=base;//base自增 
        b>>=1;//b右移,这样可以一直判断最右边那一位 
    }
    cout<<ans<<endl;
    return 0;
}

Modulo operation has the following properties

\((A+B) mod b=(A mod b+B mod b) mod b\)

\((A×B) mod b ==((A mod b)×(B mod b)) mod b\)

and so

\ (A ^ B \) \ (MOD \) \ (K \) code is as follows

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

int main()
{
    long long a, b,k;
    scanf("%lld%lld%lld",&a,&b,&k);
    if(a==k)//特判,如1 0 1 
    {
        printf("%lld^%lld mod %lld=0",a,b,k);
        return 0;
    }
    long long t=b;//将b的值保存下来用来输出 
    long long base=a,ans=1;//赋初值 
    while(t>0) 
    {
        if(t&1)//按位与0001,只有最右边同为1才执行 
        {
            ans*=base;
            ans%=k;
        }
        cout<<ans<<endl;
        base*=base;//base自增 
        base%=k;
        t>>=1;//b右移,这样可以一直判断最右边那一位 
    }
    printf("%lld^%lld mod %lld=%lld",a,b,k,ans);
    return 0;
}

2. Source Luo Gu topic P1010 a power of
seeing this question recursive explanations heart is shocked, could be so simple, recursive nb! Man of few words said on the code.

#include<bits/stdc++.h>
using namespace std;

string fun(int t,int i=0,string s="");

int main()
{
    int n;
    cin>>n;
    cout<<fun(n)<<endl;
    return 0;
}

string fun(int t,int i,string s)
{
    if(t==0)//如果次数是0就返回0 
    {
        return "0";
    }
    while(t)//快速幂,下面会再贴一个更简洁的快速幂代码 
    {
        if(t&1) 
        {
            s=(i==1?"2":"2("+fun(i)+")")+(s==""?"":"+")+s;//第一个括号内是递归主体,第二个括号判断是否是最后一位来决定是否输出括号,最后一个用来从高位到低位连接字符串
        }
        t>>=1;
        i++;//次数+1 
    };
    return s;
}

↓ more compact rapid power code is as follows

do
{
    if(t&1)
    {
        s=(i==1?"2":"2("+fun(i)+")")+(s==""?"":"+")+s;
    }
}while(i++,t>>=1);

Guess you like

Origin www.cnblogs.com/JMWan233/p/11140833.html