2

I was certain i had my code right, however it returns 1364 rather than the correct answer 1366. I tested my code for 2^15 and it returned the correct answer 26. I also tried a few other numbers, all of which gave me a correct answer. I know my code is very elementary, i don't know much Javascript and i am open to alternate solutions, however i am looking for an explanation as to why my code does not work.

//adds digits of this number
sum(Math.pow(2,1000));

function sum(x) {
    //the upper limit of the number
    var c = Math.floor(Math.log10(x));

    //the sum
    var s = 0;

    //the ith digit
    var a;

    for (var i = c; i >= 0; i--) {
        //this works, test by removing the slashes before console.log(a)
        a = Math.floor((x % Math.pow(10,i+1)) / Math.pow(10,i));
        s += a;
        //console.log(a);
    }

    console.log(s);
}
Jacob Lee
  • 73
  • 3
  • `Math.pow(2,1000) > Number.MAX_SAFE_INTEGER`. See http://stackoverflow.com/questions/43614407/how-do-i-add-1-to-a-big-integer-represented-as-a-string-in-javascript/43614550#43614550 – guest271314 Apr 29 '17 at 06:32

1 Answers1

0

Expanding on guest271314's comment:

Javascript numbers have IEEE 754 double-precision floating point behavior. This means that Javascript is unable to accurately represent integers above 253.

> Number.isSafeInteger(Math.pow(2, 15))
< true
> Number.isSafeInteger(Math.pow(2, 1000))
< false

To solve this problem in Javascript, you will need a different representation of 21000. Since the only operations you care about are exponentiation and reading out digits base 10, one possible representation is a decimal string, implementing multiplication yourself.

ephemient
  • 198,619
  • 38
  • 280
  • 391