Spread the love

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

.boat port 1200

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:

  1. Understand the Range:
    • The range is defined by a and b. This means that you’ll calculate for each number from a to b inclusive.
  2. Raise Each Number to the Power:
    • For each number nn in the range, calculate npn^p.
  3. 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:

  1. Function Definition:
    • The function sum_of_powers takes three arguments: a, b, and p.
    • a and b define the range, and p is the power to which each number in this range will be raised.
  2. Initialization:
    • total_sum is initialized to 0. This will store the sum of all the numbers raised to the power p.
  3. Loop Through the Range:
    • A for loop iterates over each number from a to b (inclusive).
    • Inside the loop, number ** p raises the current number to the power p.
    • The result is added to total_sum.
  4. 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.
  5. Example Execution:
    • With a = 1, b = 3, and p = 2, the function will calculate 12+22+321^2 + 2^2 + 3^2, which results in 14.

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.


techbloggerworld.com

Nagendra Kumar Sharma I Am Software engineer

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *