w3resource

JavaScript: Get the sum of the powers of all the numbers from start to end

JavaScript fundamental (ES6 Syntax): Exercise-135 with Solution

Sum of Powers in Range

Write a JavaScript program to get the sum of the powers of all the numbers from start to end (both inclusive).

  • Use Array.prototype.fill() to create an array of all the numbers in the target range.
  • Use Array.prototype.map() and the exponent operator (**) to raise them to power and Array.prototype.reduce() to add them together.
  • Omit the second argument, power, to use a default power of 2.
  • Omit the third argument, start, to use a default starting value of 1.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2

// Define the 'sumPower' function.
const sumPower = (end, power = 2, start = 1) =>
  // Create an array from 'start' to 'end', apply the power operation, and then sum the elements.
  Array(end + 1 - start)
    .fill(0) // Fill the array with zeros.
    .map((x, i) => (i + start) ** power) // Apply the power operation to each element.
    .reduce((a, b) => a + b, 0); // Sum all the elements.

// Test the 'sumPower' function with various arguments.
console.log(sumPower(10)); // Output: 385 (1^2 + 2^2 + ... + 10^2)
console.log(sumPower(10, 3)); // Output: 3025 (1^3 + 2^3 + ... + 10^3)
console.log(sumPower(10, 3, 5)); // Output: 2925 (5^3 + 6^3 + ... + 10^3)

Output:

385
3025
2925

Visual Presentation:

JavaScript Fundamental: Get the sum of the powers of all the numbers from start to end.
JavaScript Fundamental: Get the sum of the powers of all the numbers from start to end.

Flowchart:

flowchart: Get the sum of the powers of all the numbers from start to end

Live Demo:

See the Pen javascript-basic-exercise-135-1 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to get the symmetric difference between two given arrays.
Next: Write a JavaScript program to generate all permutations of a string (contains duplicates).

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-135.php