Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

math - Sum of numbers with exponent (N and P) in Python

I need to make a Python program that asks for two numbers. N is the first number and P the second, the program must calculate the sum of the first N numbers raised to the value P, following this formula: 1^P + 2^P + 3^P + 4^P... + N^P

If I enter, for example, 3 and 5, it will do the following calculation: 1^5 + 2^5 + 3^5 = 276

This is what I currently have:


num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
sum = float(num1) ** float(num2)
print('{0} raised to the power of {1} is {2}'.format(num1, num2, sum))

The problem is that I don't know how to make the program calculate that if the first number I enter is 3 and the second is 5, do 1 ^ 5 + 2 ^ 5 + 3 ^ 5, instead of just doing 3 ^ 5 (like my program does). Can someone help me? Thanks a lot!

question from:https://stackoverflow.com/questions/65946913/sum-of-numbers-with-exponent-n-and-p-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As @Gino Mempin said, loops are a good start.

def sum_exponents(end_num, exp):
    sum_ = 0
    for n in range(int(end_num)):
        n += 1
        sum_ += n ** float(exp)
    return sum_

num1 = input('Enter first number: ')
num2 = input('Enter second number: ')

print('{0} raised to the power of {1} is {2}'.format(num1, num2, sum_exponents(num1, num2)))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...