HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Sum of powers in range

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
sumjavascriptrangepowers

Problem

Calculating the sum of the powers of all the numbers from start to end (both inclusive) can be done using a combination of array methods and JavaScript's exponentiation operator (**).
Using Array.from(), we create an array of the appropriate size. Then, we iterate over all elements, using Array.prototype.reduce(), and calculate the sum of their powers. In order to get the value of each element, we add the start value to the current index i, then use the exponentiation operator (**) to raise it to the power.
Omitting the power argument will default to a power of 2, and omitting the start argument will default to a starting value of 1.
<baseline-support featureId="exponentiation">
</baseline-support>

Solution

const sumPower = (end, power = 2, start = 1) =>
  Array.from({ length: end + 1 - start }).reduce(
    (acc, _, i) => acc + (i + start) ** power, 0
  );

sumPower(10); // 385
sumPower(10, 3); // 3025
sumPower(10, 3, 5); // 2925


Omitting the power argument will default to a power of 2, and omitting the start argument will default to a starting value of 1.
<baseline-support featureId="exponentiation">
</baseline-support>
> [!NOTE]
>
> If you're working with older browsers or environments that don't support the exponentiation operator (**), you can use Math.pow() instead.

Code Snippets

const sumPower = (end, power = 2, start = 1) =>
  Array.from({ length: end + 1 - start }).reduce(
    (acc, _, i) => acc + (i + start) ** power, 0
  );

sumPower(10); // 385
sumPower(10, 3); // 3025
sumPower(10, 3, 5); // 2925

Context

From 30-seconds-of-code: sum-powers-in-range

Revisions (0)

No revisions yet.