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.

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

报告相同问题?

悬赏问题

  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播