猿问

Project Euler 16 - 帮助解决它

我正在解决Project Euler question 16,我最终得到了一个可以在逻辑上解决它的代码,但无法处理,因为我认为它溢出或什么?我尝试用 int64 代替 int,但它只打印 0,0。如果我将功率更改为低于 30 的任何值,它可以工作,但高于 30 则不起作用,有人能指出我的错误吗?我相信它无法计算 2^1000。


// PE_16 project main.go

package main


import (

    "fmt"

)


func power(x, y int) int {

    var pow int

    var final int

    final = 1

    for pow = 1; pow <= y; pow++ {

        final = final * x

    }

    return final

}


func main() {

    var stp int

    var sumfdigits int

    var u, t, h, th, tth, l int

    stp = power(2,1000)

    fmt.Println(stp)

    u = stp / 1 % 10

    t = stp / 10 % 10

    h = stp / 100 % 10

    th = stp / 1000 % 10

    tth = stp / 10000 % 10

    l = stp / 100000 % 10

    sumfdigits = u + t + h + th + tth + l

    fmt.Println(sumfdigits)

}


森林海
浏览 225回答 3
3回答

智慧大石

您不需要使用math/big. 下面是一个小学生将十进制数加倍的数学方法作为提示!xs以最不重要的一阶保存十进制数字。传入指向数字 ( pxs)的指针,因为切片可能需要变大。func double(pxs *[]int) {&nbsp; &nbsp; xs := *pxs&nbsp; &nbsp; carry := 0&nbsp; &nbsp; for i, x := range xs {&nbsp; &nbsp; &nbsp; &nbsp; n := x*2 + carry&nbsp; &nbsp; &nbsp; &nbsp; if n >= 10 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; carry = 1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; n -= 10&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; carry = 0&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; xs[i] = n&nbsp; &nbsp; }&nbsp; &nbsp; if carry != 0 {&nbsp; &nbsp; &nbsp; &nbsp; *pxs = append(xs, carry)&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Go
我要回答