我一直收到错误“
不能将(类型为int)用作math.Pow参数中的类型float64,不能将x(类型为int)用作math.Pow参数中的类型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
}
发布于 2020-09-29 05:36:53
func powInt(x, y int) int {
return int(math.Pow(float64(x), float64(y)))
}
以防你不得不重复使用它并保持它的清洁。
发布于 2021-03-02 05:01:55
如果您的输入是
并且输出总是期望为
,然后您将处理32位数字。编写自己的函数来处理这种乘法比使用
..。
,如其他答案中所述,需要64位值。
下面是15^15的基准比较(接近32位表示的上限):
// IntPow calculates n to the mth power
func IntPow(n, m int) int {
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
我相信最好的
解决方案
您应该编写自己的函数,类似于
如上所示。我的测试表明,它在单个CPU核心上的运行速度比在单个CPU内核上运行的速度快4倍以上。
..。
https://stackoverflow.com/questions/64108933
复制相似问题