Python Program to Find Sum of Odd Numbers
num % 2 != 0, for example: sum_odd = sum(x for x in range(1, n+1) if x % 2 != 0).Examples
How to Think About It
Algorithm
Code
n = int(input("Enter a number: ")) sum_odd = 0 for num in range(1, n + 1): if num % 2 != 0: sum_odd += num print("Sum of odd numbers:", sum_odd)
Dry Run
Let's trace the input 5 through the code
Input
n = 5
Initialize sum
sum_odd = 0
Loop start
num = 1, check 1 % 2 != 0 (True), sum_odd = 0 + 1 = 1
Next iteration
num = 2, check 2 % 2 != 0 (False), sum_odd = 1
Next iteration
num = 3, check 3 % 2 != 0 (True), sum_odd = 1 + 3 = 4
Next iteration
num = 4, check 4 % 2 != 0 (False), sum_odd = 4
Next iteration
num = 5, check 5 % 2 != 0 (True), sum_odd = 4 + 5 = 9
Loop end
sum_odd = 9
| num | num % 2 != 0 | sum_odd |
|---|---|---|
| 1 | True | 1 |
| 2 | False | 1 |
| 3 | True | 4 |
| 4 | False | 4 |
| 5 | True | 9 |
Why This Works
Step 1: Check each number
The code checks every number from 1 to n to see if it is odd using num % 2 != 0.
Step 2: Add odd numbers
Only numbers that are odd are added to the running total sum_odd.
Step 3: Final sum
After checking all numbers, the total sum of odd numbers is printed.
Alternative Approaches
n = int(input("Enter a number: ")) sum_odd = sum([x for x in range(1, n+1) if x % 2 != 0]) print("Sum of odd numbers:", sum_odd)
n = int(input("Enter a number: ")) k = (n + 1) // 2 sum_odd = k * k print("Sum of odd numbers:", sum_odd)
Complexity: O(n) time, O(1) space
Time Complexity
The program loops through all numbers from 1 to n once, so it takes linear time O(n).
Space Complexity
It uses a fixed amount of extra space for the sum variable, so space complexity is O(1).
Which Approach is Fastest?
The arithmetic formula approach is fastest with O(1) time, while looping and list comprehension are O(n).
| Approach | Time | Space | Best For |
|---|---|---|---|
| Loop with if condition | O(n) | O(1) | Simple and clear for beginners |
| List comprehension with sum() | O(n) | O(n) | Concise code but uses more memory |
| Arithmetic formula | O(1) | O(1) | Fastest for sum of first k odd numbers |
num % 2 != 0 to check if a number is odd in Python.num % 2 == 0 which checks for even numbers instead of odd.