我正在使用Python,我想找到2个数字之间的整数之和:
number1 = 2
number2 = 6
ans = (?)
print ans
#the numbers in between are 3,4,5
Run Code Online (Sandbox Code Playgroud)
请给我数学公式或Python代码来做到这一点.
暗示:
给定两个数字A和B(包括两者),其中B> A,A和B之间的值之和由下式给出
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
Run Code Online (Sandbox Code Playgroud)
如果A&B都是独家的,那么将B替换为B - 1,A替换为A + 1.剩下的我作为练习留给你
通读Python Expression将数学表达式转换为Python代码
注意 不幸的是,SO不支持MathJax,否则上面的表达式可能已经更好地格式化了