Reputation: 13
I need to write a code that asks for user input 'num' of any number and calculates the sum of all odd numbers in the range of 1 to num. I can't seem to figure out how to write this code, because we had a similar question about adding the even numbers in a range that I was able to figure out.
I've also added the lines of code that I've written already for any critiques of what I may have done right/wrong. Would greatly appreciate any help with this :)
total = 0
for i in range(0, num + 1, 1):
total = total + i
return total
Upvotes: 0
Views: 4294
Reputation: 27547
num = int(input("Input an odd number: "))
total = (1+num)**2//4
print(total)
Input an odd number: 19
100
Upvotes: 1
Reputation: 5788
Using filter:
start_num = 42
end_num = 500
step = 7
sum([*filter(lambda x: x % 2 == 1, [*range(start_num, end_num+1, step)])])
Upvotes: 1
Reputation: 7211
total = sum(range(1, num + 1, 2))
if you really need a for loop:
total = 0
for i in range(1, num+1, 2):
total += i
and to make it more exotic, you can consider the property that i%2==1
only for odd numbers and i%2==0
for even numbers (caution: you make your code unreadable)
total = 0
for i in range(1, num+1):
total += i * (i % 2)
You can invent a lot more ways to solve this problem by exploiting the even-odd properties, such as:
(-1)^i
is 1 or -1i & 0x1
is 0 or 1abs(((1j)**i).real)
is 0 or 1and so on
Upvotes: 5
Reputation: 3856
Easiest solution
You can use math formula
#sum of odd numbers till n
def n_odd_sum(n):
return ((n+1)//2)**2
print(n_odd_sum(1))
print(n_odd_sum(2))
print(n_odd_sum(3))
print(n_odd_sum(4))
print(n_odd_sum(5))
1
1
4
4
9
Upvotes: 1
Reputation: 41
The range function has three parameters: start, stop, and step.
For instance: for i in range(1, 100, 2)
will loop from 1-99 on odd numbers.
Upvotes: 2
Reputation: 290
total = 0
num = int(input())
for i in range(num+1):
if i%2 == 1:
total += i
print (total)
The %
operator returns the remainder, in this case, the remainder when you divide n/2. If that is 1, it means your number is odd, you can add that to your total.
You can of course do it in 1 line with python, but this might be easier to understand.
Upvotes: 0