Sum of all integers between two integers [closed]

99封情书 提交于 2019-12-02 23:54:55

问题


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.



来源:https://stackoverflow.com/questions/15591547/sum-of-all-integers-between-two-integers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!