MCPcopy Index your code
hub / github.com/TheAlgorithms/Go / Exponentiation

Function Exponentiation

math/modular/exponentiation.go:24–50  ·  view source on GitHub ↗

Exponentiation returns base^exponent % mod

(base, exponent, mod int64)

Source from the content-addressed store, hash-verified

22
23// Exponentiation returns base^exponent % mod
24func Exponentiation(base, exponent, mod int64) (int64, error) {
25 if mod == 1 {
26 return 0, nil
27 }
28
29 if exponent < 0 {
30 return -1, ErrorNegativeExponent
31 }
32 _, err := Multiply64BitInt(mod-1, mod-1)
33
34 if err != nil {
35 return -1, err
36 }
37
38 var result int64 = 1
39
40 base = base % mod
41
42 for exponent > 0 {
43 if exponent%2 == 1 {
44 result = (result * base) % mod
45 }
46 exponent = exponent >> 1
47 base = (base * base) % mod
48 }
49 return result, nil
50}
51
52// Multiply64BitInt Checking if the integer multiplication overflows
53func Multiply64BitInt(left, right int64) (int64, error) {

Callers 5

EncryptFunction · 0.92
DecryptFunction · 0.92
MillerTestFunction · 0.92
TestExponentiationFunction · 0.85
BenchmarkExponentiationFunction · 0.85

Calls 1

Multiply64BitIntFunction · 0.85

Tested by 2

TestExponentiationFunction · 0.68
BenchmarkExponentiationFunction · 0.68