如何在Golang中使用Math.Pow和整数



我一直得到错误">不能在数学参数中使用(类型int(作为类型float64。Pow,不能在数学参数中使用x(类型int(作为类型float64。Pow,无效操作:数学。Pow(a,x(%n(float64和int类型不匹配(";

func pPrime(n int) bool {
var nm1 int = n - 1
var x int = nm1/2
a := 1;
for  a < n {
if  (math.Pow(a, x)) % n == nm1 {
return true
}
}
return false
}
func powInt(x, y int) int {
return int(math.Pow(float64(x), float64(y)))
}

以防你不得不重复使用它并保持它的清洁。

如果您的输入是int,而输出总是预期为int,那么您处理的是32位数字。编写自己的函数来处理这个乘法比使用math.Pow更有效。如其他答案中所述,math.Pow期望64位值。

以下是15^15的基准比较(接近32位表示的上限(:

// IntPow calculates n to the mth power. Since the result is an int, it is assumed that m is a positive power
func IntPow(n, m int) int {
if m == 0 {
return 1
}
result := n
for i := 2; i <= m; i++ {
result *= n
}
return result
}
// MathPow calculates n to the mth power with the math.Pow() function
func MathPow(n, m int) int {
return int(math.Pow(float64(n), float64(m)))
}

结果:

go test -cpu=1 -bench=.
goos: darwin
goarch: amd64
pkg: pow
BenchmarkIntPow15   195415786            6.06 ns/op
BenchmarkMathPow15  40776524            27.8 ns/op

我认为最好的解决方案是您应该编写自己的函数,类似于上面显示的IntPow(m, n int)。我的基准测试表明,与使用math.Pow相比,它在单个CPU内核上的运行速度快了4倍多。

由于没有人提到对整数xn执行Pow(x, n)的有效方法(对数(,如果您想自己实现它,如下所示:

// Assumption: n >= 0
func PowInts(x, n int) int {
if n == 0 { return 1 }
if n == 1 { return x }
y := PowInts(x, n/2)
if n % 2 == 0 { return y*y }
return x*y*y
}

虽然Eissa对高效解决方案的上述回答在技术上是正确的,但递归可能会降低性能。请参阅实现基于整数的幂函数pow(int,int(的最有效方法,以获得更优化的解决方案。以下是翻译成Go的C解决方案:

func IntPow(base, exp int) int {
result := 1
for {
if exp & 1 == 1 {
result *= base
}
exp >>= 1
if exp == 0 {
break
}
base *= base
}
return result
}

在我的基准测试中,这几乎是递归版本的两倍快。

如果您想要整数的精确求幂,请使用(*big.Int(.Exp.您可能会很快用大于2的幂溢出int64。

最新更新