[Algorithm]: Fast Power

Given a, i and n, find a^i mod n

Calculating fast power is very commonly used in algorithms, and the time complexity of the fastest computing fast power is O(log i)

C++

#include <iostream>
using namespace std;

long long pow_mod(long long a, long long i, long long n) {
    
    
    if (i == 0) return 1 % n;
    long long temp = pow_mod(a, i >> 1, n);
    temp = temp * temp % n;
    if (i & 1) temp = temp * a % n;
    return temp;
}

int main() {
    
    
    long long a = 29, i = 8, n = 11;
    long long res = pow_mod(a, i, n);
    cout << res << endl;
    return 0;
}

Insert picture description here

JAVA

public class PowMod {
    
    
    public static void main(String[] args) {
    
    
        long a = 29, i = 8, n = 11;
        long res = pow_mod(a, i, n);
        System.out.println(res);
    }

    private static long pow_mod(long a, long i, long n) {
    
    
        if (i == 0) return 1 % n;
        long temp = pow_mod(a, i >> 1, n);
        temp = temp * temp % n;
        if ((i & 1) != 0) temp = temp * a % n;
        return temp;
    }
}

Python

def pow_mod(a, i, n):
    if i == 0:
        return 1 % n
    temp = pow_mod(a, i >> 1, n)
    temp = temp * temp % n
    if (i & 1) != 0:
        temp = temp * a % n
    return temp


if __name__ == '__main__':
    a = 29
    i = 8
    n = 11
    res = pow_mod(a, i, n)
    print(res)

Guess you like

Origin blog.csdn.net/qq_27198345/article/details/109704029