dongti7838 2013-04-23 08:50
浏览 27
已采纳

欧拉16号项目-帮助解决该问题

I'm solving Project Euler problem 16, I've ended up with a code that can logically solve it, but is unable to process as I believe its overflowing or something? I tried int64 in place of int but it just prints 0,0. If i change the power to anything below 30 it works, but above 30 it does not work, Can anyone point out my mistake? I believe its not able to calculate 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)
}
  • 写回答

3条回答 默认 最新

  • dpfl37651 2013-04-23 08:59
    关注

    Your approach to this problem requires exact integer math up to 1000 bits in size. But you're using int which is 32 or 64 bits. math/big.Int can handle such task. I intentionally do not provide a ready made solution using big.Int as I assume your goal is to learn by doing it by yourself, which I believe is the intent of Project Euler.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么