0

I've written what I think should be a working solution to Project Euler 16 in JavaScript, and it tests well for small powers of 2 - but arrives at an incorrect result for 2^n where n = 1000. Here is my code:

function problem16(n) {

    var prod = Math.pow(2, n);
    console.log ("Prod: "+ prod);
    var sum = 0;

    while (prod >=1) {
        console.log ("Sum term: " + prod%10);

        sum += prod%10;
        console.log ("Sum: "+ sum);

        prod = Math.floor(prod / 10);
        console.log ("Prod: "+ prod);
        console.log ("------------");
        }
    return sum;

}

console.log("Sum is: " + problem16(1000));

Any help much appreciated.

2 Answers 2

1

JavaScript numbers are 64-bit floating point values. (See the spec.) They have limited precision, so once you get above a certain value, not all integers can be represented exactly. I'm fairly certain that not all numbers of the form 21000 / 10n can be represented exactly. You're going to have to find another (more clever) approach to Project Euler 16. (You shouldn't be surprised at this. Project Euler problems are not intended to simply exercise basic programming skills.)

2
  • Kudo's for not solving the problem for them.
    – Jorg
    Mar 18, 2014 at 3:51
  • Great input, thank you! I'll find some more ingenious ways to solve this :) Mar 18, 2014 at 5:55
1

I think you should try to use BigInt(). It's a build-in object that provides a way to represent whole number larger than (2^53).

I tried using BigInt() in my code to solve the same problem and it works. Here's my code :

  function powerSum(num){
  let result = String(BigInt(Math.pow(2,num)));
  let sum = 0;
  result = result.split('');
  for(let item of result){
    sum += parseInt(item);
  }
  console.log(sum);

};

powerSum(1000);
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.