Sum up all the integers in range()
Since you know the first number in this range that is divisible by 3 is 102, you can do the following:
Solution:
>>> sum(range(102, 2001, 3))
664650
To make it into a robust function:
def sum_range_divisible(start, end, divisor):
while start % divisor != 0:
start += 1
return sum(range(start, end, divisor))
Using it:
>>> sum_range_divisible(100, 2001, 3)
664650
Note:
The advantage here is that you do not have to check each number in the whole range, since you are jumping by 3 each time.
Timing:
I have timed the different solutions, mine and aga's:
>>> import timeit
>>> timeit.Timer('sum(range(102, 2001, 3))').repeat()
[9.516391893850312, 9.49330620765817, 9.508695564438462]
>>> timeit.Timer('sum(x for x in range(100, 2001) if x % 3 == 0)').repeat()
[134.757627812011, 134.46399066622394, 138.34528734198346]
Conclusion:
My answer is faster by a factor of 14
Use generator expression and sum function here:
res = sum(x for x in range(100, 2001) if x % 3 == 0)
It's pretty self-explanatory code: you're summing all the numbers from 100 to 2000, inclusive, which are divisible by three.