1
import java.math.*;

public class PowerDigitSum {
    public static void main(String[] args) {
        double[] digits ;
        digits = new double[302];
        double i = Math.pow(2, 1000);
        double c = 301;
        double c1 = 0;
        double d = 0;
        while(c>=0) {
            c1 = Math.pow(10, c);
            d = Math.floor(i/c1);
            i = i - d*c1;
            digits[(int)c] = (int)d;
            c = c-1;
        }
        double sum = 0;
        c = 0;
        while (c<302) {
            sum = sum+digits[(int)c];
            c= c+1;
        }
        System.out.println(sum);
    }
}

The output is 1281 but that's not correct according to projecteuler. What am I doing wrong?

khelwood
  • 55,782
  • 14
  • 81
  • 108
kiamf80
  • 11
  • 1
  • 6
    You can't do correct math with double values that large due to their limited nature. Use BigDecimal, or in your case BigInteger is sufficient. – Clashsoft Nov 07 '19 at 09:33
  • 1
    @deHaar, why? It's not like that's a hard number to compute, you just need about 1000 bits to store it (use uint1000, if you will), set the most significant bit to 1 and the rest to 0 and there you go. – M. Prokhorov Nov 07 '19 at 09:38
  • @M.Prokhorov it's too big for simple data types... Storing them in bits will of course do... But correct: The comment was unqualified. – deHaar Nov 07 '19 at 09:41
  • `String.valueOf(BigInteger.valueOf(2).pow(1000)).chars().map(i -> i - 48).sum()`... Just another way of doing it. – ernest_k Nov 07 '19 at 09:44
  • 1
    @ernest_k More readable: `BigInteger.TWO.pow(1000).toString().chars().map(c -> c - '0').sum()` – Andreas Nov 07 '19 at 09:45
  • print the digits you are summing and you will see that soon (after about 20 digits) you'll get only zeroes. – Hans Kesting Nov 07 '19 at 09:46
  • @Andreas, I'd still prefer `Character::getNumericValue`. – M. Prokhorov Nov 07 '19 at 09:47
  • @Andreas Agreed, more readable (Didn't know about `TWO` - another java9 addition) – ernest_k Nov 07 '19 at 09:49
  • 1
    Thread on Code Review about the same question: https://codereview.stackexchange.com/questions/228838/project-euler-16-sum-of-all-digits-of-21000 – Thilo Nov 07 '19 at 09:51

1 Answers1

0

You can't do correct math with double values that large due to their limited nature.

You could probably fix your code with BigDecimal, but it is much easier using BigInteger. Hint: it has a pow method, and you can work out the digit sum starting from toString.

Clashsoft
  • 11,553
  • 5
  • 40
  • 79
  • I don't know what the goal of Project Euler is, but is using a BigInteger library cheating? – Thilo Nov 07 '19 at 09:45
  • Accepted answer over at https://stackoverflow.com/a/19310209/14955 also uses BigInteger, so ... – Thilo Nov 07 '19 at 09:50