Reputation: 169
Given: Two positive integers a and b (a
Return: The sum of all odd integers from a through b, inclusively.
#My code:
a = 100
b = 200
for i in range(a,b):
if i%2 == 1:
print i
At the moment it's just showing a drop down list of all the odd integers. I do not know how to affix a "range" to this properly, if need be. How can I add on to my code above to get the sum of all the odd integers?
Thanks
Upvotes: 1
Views: 22598
Reputation: 77107
There are a bunch of ways to do this. If you think about the math, though, it's a lot like Gauss's old problem. Gauss was asked to add the numbers between 1 and 100, and he realized that each pair of high and low values summed to 101 (100 + 1, 99 + 2, 98 + 3…)
high = b
low = a
So we have to multiply some number of b + a
values. How many are there? For all the integers, that's just
num_pairs = (high-low) // 2
Then we multiply that number by high + low
to get the answer:
result = (high + low) * num_pairs
But you only want every other ones, so we divide by two again:
result //= 2
Totally:
def sumrange(low, high, step):
num_pairs = (high - low) // 2
result = (high + low) * num_pairs
return result // step
or sumrange = lambda low, high, step: (high - low) * (high + low) // (2 * step)
Now this still isn't quite an answer to your question, because it needs to be offset depending on whether your low value is odd, and whether your high value is included or excluded. But I will leave that as an exercise.
Making this a CW answer so someone can edit if my math is messy.
Upvotes: 1
Reputation: 1902
And the numpy version of the solution:
import numpy as np
a = 100
b = 200
r = np.linspace(a,b-1,b-a)
r = np.sum(np.mod(r,2)*r)
print(r)
Upvotes: 0
Reputation: 483
Some mathematical tricks can solve your problem much efficiently.
For example, sum of first n odd numbers = n*n square(n)
So you can use for
Sum of odd numbers [m,n] = n*n - (m-2)*(m-2)
where m!=1
andm and n are odds
One more useful analysis is, AP (arithmetic progression)
Formula : (n/2)*(a+l)
where n= no. of elements, a = first term, l= last term
Here,
a = m [if m is odd]
a = m+1 [if m is even]
l = n [if n is odd]
l = n-1 [if n is even]
n = ( ( l - a ) / 2 ) + 1
By applying in code, you can easily get the answer...
Upvotes: 0
Reputation: 10170
Sum all the numbers between a
and b
if odd.
sum(i for i in xrange(a, b) if i%2)
Upvotes: 4
Reputation: 5996
A rather quick way to do it would be:
result = 0
for i in range(a,b+1):
if i%2 == 1:
result += i
print result
Upvotes: 3