chi*_*oel 3 floating-point integer type-conversion go
我不断收到错误“不能在 math.Pow 的参数中使用 (type int) 作为 float64 类型,不能在 math.Pow 的参数中使用 x (type int) 作为 float64 类型,无效操作:math.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
}
Run Code Online (Sandbox Code Playgroud)
Chr*_*non 13
如果您的输入为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
}
if m == 1 {
return n
}
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)))
}
Run Code Online (Sandbox Code Playgroud)
结果:
go test -cpu=1 -bench=.
goos: darwin
goarch: amd64
pkg: pow
BenchmarkIntPow15 195415786 6.06 ns/op
BenchmarkMathPow15 40776524 27.8 ns/op
Run Code Online (Sandbox Code Playgroud)
我相信最好的解决方案是您应该编写自己的函数,类似于IntPow(m, n int)上面所示的函数。我的基准测试表明,与使用math.Pow.
Eis*_* N. 10
Pow(x, n)由于没有人提到处理整数的有效方法(对数)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
}
Run Code Online (Sandbox Code Playgroud)
小智 5
func powInt(x, y int) int {
return int(math.Pow(float64(x), float64(y)))
}
Run Code Online (Sandbox Code Playgroud)
以防万一您必须重复使用它并保持清洁。