First, think about the question itself. What does 'between' truly mean in your case? If I were to choose 5
and 10
as numbers, would 5
and/or 10
be included, or not?
Second, the mathematical question. How to calculate it?
There are multiple ways, and they are not equally efficient. calculating the sum of all numbers between two numbers with a loop is inefficient for a large difference.
But as I am sure, your teacher gave you a hint, which is that the sum of all numbers from 1
to n
is n * (n + 1) / 2
. However this function will give you the sum of all positive numbers up to n
, but you only want the ones starting from another. I will leave it up to you to figure out this (easy) solution yourself, as that is more rewarding than being spoonfed the answer.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…