Introduction
In this lab, we will explore a JavaScript function that calculates the sum of powers in a given range of numbers. You will learn how to use built-in array methods such as fill(), map(), and reduce() to perform mathematical operations efficiently. Additionally, you will have the opportunity to customize the function's input parameters to suit your needs.
Function to Calculate Sum of Powers in a Given Range
To calculate the sum of the powers of all the numbers within a specified range (including both endpoints), use the following function:
const sumPower = (end, power = 2, start = 1) =>
Array(end + 1 - start)
.fill(0)
.map((x, i) => (i + start) ** power)
.reduce((a, b) => a + b, 0);
Here's how you can use this function:
- Call
sumPower(end)to calculate the sum of squares of all numbers from 1 toend. - Call
sumPower(end, power)to calculate the sum ofpowerth powers of all numbers from 1 toend. - Call
sumPower(end, power, start)to calculate the sum ofpowerth powers of all numbers fromstarttoend.
Note that the second and third arguments (power and start) are optional, and default to 2 and 1 respectively if not provided.
Example:
sumPower(10); // Returns 385 (sum of squares of numbers from 1 to 10)
sumPower(10, 3); // Returns 3025 (sum of cubes of numbers from 1 to 10)
sumPower(10, 3, 5); // Returns 2925 (sum of cubes of numbers from 5 to 10)
Summary
Congratulations! You have completed the Sum of Powers in Range lab. You can practice more labs in LabEx to improve your skills.