0

i am getting answer 659 but that one is wrong answer please check it one's. this is my code

var fact=1;

for(var i=1;i<=100;i++){

fact  = fact*i;

}

var sum = 0;

while (fact > 0) {

sum += fact % 10;

fact = Math.floor(fact / 10);
}
console.log(sum);
Dep
  • 71
  • 2
  • 4
  • 13

2 Answers2

1

There's a syntax error in the definition of length - the var keyword should come before it, not after it, and a similar problem in the calculation of sum.

Regardless, I think that converting the number to a string is the hard way to go at it. You can use the % operator to get the last digit and divide the number by 10 (don't forget to floor!) until you're done with all the digits:

var sum = 0;
while (fact > 0) {
    sum += fact % 10;
    fact = Math.floor(fact / 10);
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

Cool. You've written a very sensible piece of code. But there are a couple things to think about. One is the gigantic size of 100!. If you go to a console and enter some code, you'll see this:

> fact=1
1
> for(i=1;i<=100;i++){fact *= i;}
9.33262154439441e+157

Crikey. 10 to the 157. Look up the largest integer js can display. It's much smaller! So if this is a programming assignment, you have to be more subtle.

Next, if you get the number, all 158 digits, and you want to add them using your strategy, you may need to convert the strings you get (a substring is a string, after all) to a Number.

But really, the question is, can you determine the sum of the digits without calculating the number?

Tim Erickson
  • 582
  • 5
  • 15