drrqwokuz71031449 2016-05-17 00:45
浏览 64
已采纳

如果y超过64,为什么pow函数返回0?

Why is the result of pow zero if y is greater than 64?

package main

import (
    "fmt"
)

func pow(x uint64, y uint64) uint64 {
    if y > 64 {
        return 0
    }
    var result uint64 = 1
    var counter uint64
    var previous uint64
    for y > 0 {
        previous = result
        result = result * x
        y = y - 1
        counter++
        if result == 0 {
            return previous
        }
    }
    return result
}

func main() {
    result1 := pow(2, 64)
    fmt.Println(result1)
    result2 := pow(2, 32)
    fmt.Println(result2)
    result3 := pow(2, 3)
    fmt.Println(result3)
}

I just realized that it is because it is in base 2. What can you say about this? (I am still new to programming and with golang.)

  • 写回答

1条回答 默认 最新

  • douyinmian8151 2016-05-17 00:56
    关注

    Your pow shouldn't be based on what is y. It would be less for bigger number.

    Use this:

    `

    // Assuming that b will never be 0
    func mult(a, b uint64) (uint64, bool) {
        result := a * b
        return result, (result/b == a)
    }
    
    func pow(x uint64, y uint64) uint64 {
    if y == 0 {
        return 1
    }
    if x == 0 {
        return 0
    }
    var result uint64 = 1
    var counter uint64
    var previous uint64
    var ok bool
    for y > 0 {
        previous = result
        result, ok = mult(result, x)
        if !ok {
            return 0
        }
    
        y = y - 1
        counter++
        if result == 0 {
            return previous
        }
    }
        return result
    }
    

    Old answer before clarification:

    Actually it should be 63. It is because uint64 can have at max can have largest number as 2 ^ (64) -1 (2 raise to the power 64 minux 1). So maximum number that can be generated for 2 power is 2 ^ 63.

    You can confirm that by running your code. It would give you same result as for all number greater that 63 if you remove the restriction of y > 64 . (9223372036854775808 or 2^63). That restriction should be y > 63.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?