Sum of Powers in Range

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") subgraph Lab Skills javascript/variables -.-> lab-28635{{"`Sum of Powers in Range`"}} javascript/data_types -.-> lab-28635{{"`Sum of Powers in Range`"}} javascript/arith_ops -.-> lab-28635{{"`Sum of Powers in Range`"}} javascript/comp_ops -.-> lab-28635{{"`Sum of Powers in Range`"}} javascript/higher_funcs -.-> lab-28635{{"`Sum of Powers in Range`"}} end

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 to end.
  • Call sumPower(end, power) to calculate the sum of powerth powers of all numbers from 1 to end.
  • Call sumPower(end, power, start) to calculate the sum of powerth powers of all numbers from start to end.

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.

Other JavaScript Tutorials you may like