Jordan Palmer
Jordan Palmer

Reputation: 11

For loop returning completely wrong value using power function

As you can see int he code below I separate the n variable and convert back to an integer array. When I put these numbers into my for loop they come out in the billions. Any help would be greatly appreciated.

var n = [86]
var p = [1]

n = n.toString().split("").map(function(value) {
    return(parseInt(value))
})
var total = 0;
for(i=0;i<n.length;i++) {
    total += (Math.pow(n[i],(p+i))
}
console.log(total)

Upvotes: 1

Views: 57

Answers (2)

EugenSunic
EugenSunic

Reputation: 13703

You need the conversion from strings to numbers and you are adding an array to numbers.

You cannot sum an array to an integer [1]+0, it doesn't result in a number. It will do a concatenation.

var n = [86]
var p = [1]
n = n.toString().split("").map(val => Number(val))
var total = 0;
for (i = 0; i < n.length; i++) {
  total += Math.pow(n[i], (p[0] + i))
}
console.log(total);

Upvotes: 1

yangcs907
yangcs907

Reputation: 21

p is an array not an individual number, in your for loop, when it is running (p+i), that value ends up being 10 and 11. So your first loop is running Math.pow(8,10) and the second time it runs it is running Math.pow(6,11), which, will result in a number in the billions

Upvotes: 0

Related Questions