两个整数之间的所有整数之和 [英] Sum of all integers between two integers

查看:200
本文介绍了两个整数之间的所有整数之和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python,我想找到2个数字之间的整数之和:

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

请给我一个数学公式或Python代码.

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

推荐答案

提示:

给出两个数字A和B(包括两个数字),其中B> A,则A与A之间的值之和为A. B由

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

如果A& B都是互斥的,然后将B替换为B-1并将A替换为A +1.其余的我留作练习之用

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

通读 Python表达式,将数学表达式转换为Python代码

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

注意 不幸的是,SO不支持MathJax,否则上述表达式的格式可能会更好

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

这篇关于两个整数之间的所有整数之和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆