I would like you to see how your loops work if b is close to 2 ^ 32 ;-) Since Matthew said there is no need for a loop, but he does not explain why.
The problem is the simple arithmetic sequence of the wiki . The sum of all elements in this sequence:
(a+b) Sn =
where "a" is the first element, the last is "b", and "n" is the number, if elements. If we make even numbers "a" and "b", we can easily solve this problem. Therefore, creating "a" and "b" is equally simple:
if ((a & 1)==1): a = a + 1 if ((b & 1)==1): b = b - 1
Now think how many elements we have between two even numbers - this is:
ba n = --- + 1 2
Put it in the equation and you get:
a+b ba Sn =
so that your code looks like this:
def sum_even(a,b): if ((a & 1)==1): a = a + 1 if ((b & 1)==1): b = b - 1 return ((a+b)/2) * (1+((ba)/2))
Of course, you can add code to prevent it from being equal to or greater than b, etc.
Artur source share