简体   繁体   中英

Python Arithmetic Sequence Sum

How do I make a code that follows this? 1⋅2+2⋅3+3⋅4+…+(n−1)⋅n

For example, if n=5 , the answer is 1⋅2+2⋅3+3⋅4+4⋅5=40.

n cannot be less than or equal to two or more or equal to 1000

This is my code for now but it doesn't work.

n = int(input())
if n>= 2 and n<=1000:
    sum = 0;
    numbers = range(1, n+1)
    for amount in numbers:
        if (amount % 2 == 1):
            sum *= amount
        else:
            sum += amount 
    print(sum)

For every number between 1 and n-1 (inclusive), you need to multiply it by the following number, and then sum them all. The easiest way to represent this is with a comprehension expression over a range call:

result = sum(i * (i + 1) for i in range(1, n))

You need to reproduce exactly the scheme you give

  • for each number, mulitply it with itself-1, and sum that
def compute(n):
    if 2 <= n <= 1000:
        total = 0
        for amount in range(1, n + 1):
            total += amount * (amount - 1)
        print(total)

But that's the same as multiplying each with itself+1, if you change the bound to get one step less

for amount in range(1,n):
    total += amount * (amount + 1)

Then you can use builtin methos sum and a generator syntax

def compute(n):
    if 2 <= n <= 1000:
        total = sum(nb * (nb + 1) for nb in range(1,n))
        print(total)

If you try to approach it mathematically, you can have the answer in a single expression.

Dry run your code. You will see that for n = 5, you are doing as follows:

Num of Iterations = 6 (1 -> 5+1)
Iteration 1
sum = 0 + 1 = 1

Iteration 2
sum = 1 * 2 = 2

Iteration 3
sum = 2 + 3 = 5

Iteration 4
sum = 5 * 4 = 20

Iteration 5 
sum = 20 + 5 = 25

Iteration 6
sum = 25 * 6 = 150

In this, you are completely disregarding the BODMAS/PEMDAS rule of multiplication over addition in the process of regenerating and calculating the series

What you need to do is

Iteration 1:
sum = 0 + 2 * 1 = 2

Iteration 2:
sum = 2 + 3 * 2 = 8

Iteration 3:
Sum = 8 + 4*3 = 20

Iteration 4:
Sum = 20 + 5*4 = 40

Here, We have broken the step as follows:

For each iteration, take the product of (n) and (n-1) and add it to the previous value

Also note that in the process, we are first multiplying and then adding. ( respecting BODMAS/PEMDAS rule ) So, you need to go from n = 2 to n = 5 and on each iteration you need to do (n-1)*(n)

As mentioned earlier, the loop is as follows:

## Checks for n if any
sum = 0
for i in range(2, n):
    sum = sum + (i-1)*i
print(sum)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM