Sum of all integers between two integers [closed]

2020-05-10 12:25发布

问题:

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 7 years ago.

I am using Python and I want to find the sum of the integers between 2 numbers:

number1 = 2
number2 = 6
ans = (?)
print ans

#the numbers in between are 3,4,5

Please give me either the mathematical formula or the Python code to do this.

回答1:

Hint:

Given two numbers A and B (both inclusive) where B > A, the sum of values between A & B is given by

B(B + 1)/2 - (A - 1)A/2
=(B^2 + B - A^2 + A)/2
=((B - A)(B + A) + (B + A))/2
=(B + A)(B - A + 1)/2

If A & B are both exclusive, then replace B with B - 1 and A with A + 1. The rest I leave it for you as an exercise

Read through the Python Expression to translate the mathematical expression to Python Code

Note Unfortunately, SO does not support MathJax or else the above expression could had been formatted better



回答2:

You need this to get the sum:

ans = number1  + number2

Or is this not what you wanted to do? Since you commented: the numbers in between are 3,4,5, do you mean this?

>>> for i in range(number1+1,number2):
...     print i
... 
3
4
5

EDIT:
So, OP also needs sum of all numbers between two numbers:

>>> number1 = 2
>>> number2 = 6
>>> sum(range(number1 + 1, number2))
12

This second part given by OP.



回答3:

I like Grijesh's answer, simple and elegant. Here is another take on it, using a recursive call:

global sum
def sum_between(a, b):
    global sum
    # base case
    if (a + 1) == b:
        return sum
    else:
        sum += (a + 1)
        return sum_between(a + 1, b)

Not as straight forward as using sum(range(a+1, b)). But simply interesting as an exercise in recursive functions.