Sum of powers in range
Problem Statement:
Given a range of numbers from a
to b
(inclusive) and an exponent p
, calculate the sum of each number in this range raised to the power of p
.
Example:
If a = 1
, b = 3
, and p = 2
, the sum would be: 12+22+32=1+4+9=141^2 + 2^2 + 3^2 = 1 + 4 + 9 = 14
Steps to Solve:
- Understand the Range:
- The range is defined by
a
andb
. This means that you’ll calculate for each number froma
tob
inclusive.
- The range is defined by
- Raise Each Number to the Power:
- For each number nn in the range, calculate npn^p.
- Sum the Results:
- Add up all these results to get the final sum.
Python Implementation:
Here’s how you can implement this in Python:
def sum_of_powers(a, b, p):
"""
Calculate the sum of powers in the range [a, b].
:param a: Start of the range (inclusive)
:param b: End of the range (inclusive)
:param p: The power to which each number is raised
:return:
The sum of each number in the range [a, b] raised to the power p
"""
total_sum = 0
for number in range(a, b + 1):
total_sum += number ** p
return total_sum
# Example usage:
a = 1
b = 3
p = 2
result = sum_of_powers(a, b, p)
print(f"The sum of powers from {a} to {b} with power {p} is: {result}")
Explanation:
- Function Definition:
- The function
sum_of_powers
takes three arguments:a
,b
, andp
. a
andb
define the range, andp
is the power to which each number in this range will be raised.
- The function
- Initialization:
total_sum
is initialized to 0. This will store the sum of all the numbers raised to the powerp
.
- Loop Through the Range:
- A
for
loop iterates over each number froma
tob
(inclusive). - Inside the loop,
number ** p
raises the currentnumber
to the powerp
. - The result is added to
total_sum
.
- A
- Return the Result:
- After the loop completes,
total_sum
will contain the sum of all the powers in the specified range, and it’s returned.
- After the loop completes,
- Example Execution:
- With
a = 1
,b = 3
, andp = 2
, the function will calculate 12+22+321^2 + 2^2 + 3^2, which results in 14.
- With
Output:
The sum of powers from 1 to 3 with power 2 is: 14
This code works for any integers a
, b
, and p
. You can modify the values of a
, b
, and p
to calculate the sum of powers for different ranges and exponents.
0 Comments