【问题标题】:Sum of digits issue数字总和问题
【发布时间】:2013-11-23 21:43:26
【问题描述】:

我正在处理 Project Euler 的一些问题,但我偶然发现了一个问题。 我不知道为什么这个算法不适用于 2^1000。它适用于 10^1 和 10^8 范围内的数字(这些是我测试过的数字),但它应该适用于每个可能的范围。

顺便说一句,2^1000 是 1.07*10^301。双精度的上限或多或少是 10^308,因此该数字仍在范围内。

import java.lang.Math;

public class Euler15 {
    public static void main(String[] args) {


        int count = 0;
        double res = Math.pow(2,1000);

        for(int i = 301; i >= 0; i--){
            if (res == 0){
                break;
            }
            while (res >= Math.pow(10, i)){
                res-= Math.pow(10, i);
                System.out.println(res);
                count++;
            }
        }

    System.out.println(count);
}
}

【问题讨论】:

  • 因为 2^1000 太大了!
  • 可能是舍入问题。
  • 仅仅因为它在double 的范围内并不意味着你得到所有数字直到单位。
  • double 精度只有 15-16 位,不管数字多大。

标签: java algorithm sum-of-digits


【解决方案1】:

2^1000 对于普通数据类型来说太大了。使用 BigInteger 或字符串。

import java.math.BigInteger;

将输入作为 BigInteger:

BigInteger n = BigInteger.valueOf(2);

现在把它加电到 1000:

n = n.pow(1000);

现在,使用toString() 将其转换为字符串,然后将每个字符添加到结果中,将其更改为int。应该这样做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-22
    • 2015-11-28
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多