Exponentiation returns base^exponent % mod
(base, exponent, mod int64)
| 22 | |
| 23 | // Exponentiation returns base^exponent % mod |
| 24 | func 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 |
| 53 | func Multiply64BitInt(left, right int64) (int64, error) { |