-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpow.go
32 lines (27 loc) · 844 Bytes
/
pow.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package maths
import (
"fmt"
"math"
)
// Pow returns the x^|y|.
// Returns 1, nil for all x and y when y is 0 or x is 1.
// If an overflow error is detected when the numbers get too large, the function returns 0, ErrOverflowDetected.
// In this case, use *bigInt.Exp() from the math/big package.
func Pow(x, y int) (int, error) {
if y == 0 || x == 1 {
return 1, nil
}
absY, err := Abs(y)
if err != nil {
return 0, fmt.Errorf("failed to get Abs(%d): %w", y, err)
}
result := x
for i := 1; i < absY; i++ {
// Check for overflow before multiplication. x could be positive or negative.
if result > math.MaxInt/x && result > math.MinInt/x {
return 0, fmt.Errorf("failed to calculate %d * %d. The result is too large to hold in an int variable: %w", result, x, ErrOverflowDetected)
}
result *= x
}
return result, nil
}