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
Example 2:
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.
Example:
Javascript
<script> // Function that return sum of // All element raised to power function PowerNo( s, num, power) { var ans = 0; for ( let i = s; i <= num; i++) { let temp = i**power; ans += temp; } return ans; } // Test variable var a1 = PowerNo(1, 5, 2); var a2 = PowerNo(1, 5, 3); var a3 = PowerNo(5, 5, 4); // Printing result console.log(a1) console.log(a2) console.log(a3) </script> |
Output :
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.
Example:
Javascript
<script> // function that perform raising number to power function PowerNo(num, i, power) { return (num + i) ** power; } // function that perform sum to all the element function SumNo(x, y) { return x + y; } // function performing map() and reduce( ) to array const sumPower = (num, s, power) => Array(num + 1 - s) .fill(0) .map((x, i) => PowerNo(s, i, power)) .reduce((x, y) => SumNo(x, y), 0); // test case var a1 = sumPower(5, 1, 2); var a2 = sumPower(5, 1, 3); var a3 = sumPower(5, 5, 4); // printing answer console.log(a1); console.log(a2); console.log(a3); </script> |
Output :
55 225 625