如何在 Golang 中将 Math.Pow 与整数一起使用

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.Powmath.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.

  • 可怕的是 Go 不包含 IntPow。您的实现在时间复杂度上是线性的,而像样的标准库应该提供具有对数复杂度的简单实现。 (6认同)
  • @cesartalves 预期的结果不会是整数,因此如果涉及负指数,则将值转换为“float64”并使用“math.Pow”将是合适的 (2认同)

Eis*_* N. 10

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

// 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)

以防万一您必须重复使用它并保持清洁。

  • 虽然这使事情变得更清晰,但我认为如果您要编写自己的接受“int”参数并返回“int”的函数,最好完全避免使用“math.Pow”。正如我在回答中提到的,使用循环自己进行乘法可以提高性能,而且还可以删除外部包依赖项 (6认同)