1

For instance, let's say I have the number 345. How can I in javascript loop through each digit in the number and raise it to the consecutive nth power: i.e. 3^1 + 4^2 + 5^3?

Colin Sygiel
  • 917
  • 6
  • 18
  • 29

4 Answers4

7

To calculate the sum using String.prototype.split() and Array.prototype.reduce():

let x = String(345).split('').reduce((a, v, i) => a + Math.pow(v, i + 1), 0);

console.log(x); // 144

Use Array.prototype.map() if, instead of calculating the sum, you want to get the consecutive powers as an array:

let a = String(345).split('').map((v, i) => Math.pow(v, i + 1));

console.log(a); // [3, 16, 125]
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
2

This converts the number to a string splits it into digits then raises each to the power of its index plus one and then reduces via addition to result in the answer:

('' + 345).split('').map(function(v, i) {
  return Math.pow(parseInt(v), i+1)
}).reduce(function(a, v) {
  return a + v
}, 0)

results in 144

Dan D.
  • 73,243
  • 15
  • 104
  • 123
0

Solution using for() loop

"use strict";

let number = 345;
let str = number.toString();
let answer = 0;

for (let i in str) answer += Math.pow(str[i], Number(i)+1);

console.log(answer);
niry
  • 3,238
  • 22
  • 34
0

Try this.

<!DOCTYPE html>
<html>

<head>
<script>
    var number = 345;
    var strNum = number.toString();
    var sum = 0;
    for(var i = 0; i < strNum.length; i++ ){
        sum += Math.pow(parseFloat(strNum[i]), i+1);
    }
    console.log(sum);
</script>
</head>

</html>
Nitheesh
  • 19,238
  • 3
  • 22
  • 49
  • 1
    Why would you repeatedly call `strNum.substring(...)` rather than just accessing the individual characters with `strNum[i]`? – nnnnnn Apr 07 '17 at 05:15
  • That is also a solution, I just developed a logic that came to my mind. – Nitheesh Apr 07 '17 at 05:18