简体   繁体   中英

How to write a for loop program that finds the sum of all odd numbers in a range, but does not use the if function

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
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 -1
  • i & 0x1 is 0 or 1
  • abs(((1j)**i).real) is 0 or 1

and so on

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.

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
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.

Using filter:

start_num = 42
end_num = 500
step = 7
sum([*filter(lambda x: x % 2 == 1, [*range(start_num, end_num+1, step)])])

You can use the math formula (works every time) :

num = int(input("Input an odd number: "))
total = (1+num)**2//4
print(total)

Output:

Input an odd number: 19
100

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM