Given three variables as Starting, Ending, and Power. Our task is to find the total sum of all the numbers between Starting and Ending inclusion to both ends raised to power.
Example 1: Starting variable 1 End 5 and Power 2. Iterate from 1 to 5 and raised each to the power of 2. Add all elements 1+4+9+16+25 which is 55.
Input: 1, 5, 2 Output: 55
Input: 1, 5, 3 Output: 225
Approach 1: We can get the desired answer by following approaches. In this approach, we use a for loop for solving our problem. The simple approach is to use for loop to iterate from starting to end and follow the steps.
- Make variable ans that store our ans.
- Raise each element to the power of Power.
- Add each raised element to ans variable.
- Return ans.
55 225 625
Approach 2: In this approach, we use map() and reduce() methods to solve our problem. The map() function is used to iterate over the array and performing function with all elements and returns a new array with modified value. The reduce() method is used to perform a function with all element, store it in one variable and returns it.
- We have Starting, Ending, and Power variable.
- Make an array of ranges from Starting range to Ending range values.
- Use the map() method in an array and raise all the numbers to the power of Power.
- Use reduce() method in the updated array and sum all the elements.
- Finally, reduce() returns the total sum.
55 225 625