快速幂算法

本文深入讲解了快速幂算法及其在取模运算中的应用,通过对比传统幂运算,展示了快速幂算法在提高运算效率上的优势。文章提供了C++实现代码,包括快速幂和快速幂取余的函数,并通过具体示例验证了算法的正确性和高效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给自己做个记录

#include <iostream>
#include <cmath>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <string>
#include <stdio.h>
#include <sstream>
#include <vector>
#include <cstddef>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <list>
using namespace std;

//快速幂,a的b次方
int Pow(int a,int b){
    int ans = 1;
    int base = a;
    //将b视为二进制,当b不为0时
    //(举个栗子:a为2,b为11,即1011,2^11 = 2^1 * 2^2 * 2^8
    while(b){
        //b与1作与,即取b的最后一位,如果为1则ans乘base
        //(取1,1,0,1,分别代表2^1,2^2,不乘,2^8
        if(b & 1)   ans *= base;
        //base一直作叠乘,保证随时可以为ans服务(取1,1,0,1时base分别等于2^1,2^2,2^4,2^8
        base *= base;
        //b右移一位
        b >>= 1;
    }

    return ans;
}
//快速幂取余
//定理:(a*b) mod c = (a mod c) * (b mod c) mod c
//推论:a^b mod c = (a mod c)^b mod c
int pow_mod(int a,int b,int c){
    int ans = 1;
    //先将base定为a mod c
    int base = a % c;
    while(b){//继续拿上个栗子,a = 2,b = 11,c = 7,即2^11 mod 7
        //一直模c是为了缩小底数的规模
        if(b & 1)   ans = (ans * base)%c;//第二次,(a mod c) * (a mod c)^2 mod c = (a mod c)^3 mod c
        base = (base*base)%c;//第一次,(a mod c)*(a mod c) mod c = (a mod c)^2 mod c
        b >>= 1;
    }

    return ans;
}
int main()
{
    //朴素算法
    cout << pow(2,11) << endl;
    //快速幂算法
    cout << Pow(2,11) << endl;
    //朴素算法
    cout << (int)pow(2,11)%7 << endl;
    //快速幂算法
    cout << pow_mod(2,11,7) << endl;



    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值