Program to find the sum of first n odd numbers in Python

In Python, finding the sum of the first n positive odd numbers is a common mathematical problem. The odd numbers sequence starts from 1, 3, 5, 7, 9, and so on. We can solve this using multiple approaches.

So, if the input is like 7, then the output will be 49 as [1+3+5+7+9+11+13] = 49

Method 1: Using While Loop

This approach iterates through the first n odd numbers and calculates their sum ?

def sum_first_n_odds(n):
    if n == 0:
        return 0
    
    total_sum = 1
    count = 0
    current_odd = 1
    
    while count < n - 1:
        current_odd += 2
        total_sum += current_odd
        count += 1
    
    return total_sum

# Test the function
n = 7
result = sum_first_n_odds(n)
print(f"Sum of first {n} odd numbers: {result}")
Sum of first 7 odd numbers: 49

Method 2: Using Mathematical Formula

The sum of first n odd numbers follows the formula: n² (n squared) ?

def sum_first_n_odds_formula(n):
    return n * n

# Test the function
n = 7
result = sum_first_n_odds_formula(n)
print(f"Sum of first {n} odd numbers: {result}")

# Verify with more examples
for i in range(1, 6):
    print(f"n = {i}: Sum = {sum_first_n_odds_formula(i)}")
Sum of first 7 odd numbers: 49
n = 1: Sum = 1
n = 2: Sum = 4
n = 3: Sum = 9
n = 4: Sum = 16
n = 5: Sum = 25

Method 3: Using For Loop

Generate the first n odd numbers using a for loop and sum them ?

def sum_first_n_odds_for_loop(n):
    if n == 0:
        return 0
    
    total_sum = 0
    for i in range(n):
        odd_number = 2 * i + 1
        total_sum += odd_number
    
    return total_sum

# Test the function
n = 7
result = sum_first_n_odds_for_loop(n)
print(f"Sum of first {n} odd numbers: {result}")

# Show the odd numbers being summed
odd_numbers = [2 * i + 1 for i in range(n)]
print(f"Odd numbers: {odd_numbers}")
print(f"Sum: {sum(odd_numbers)}")
Sum of first 7 odd numbers: 49
Odd numbers: [1, 3, 5, 7, 9, 11, 13]
Sum: 49

Comparison

Method Time Complexity Space Complexity Best For
While Loop O(n) O(1) Understanding the logic
Mathematical Formula O(1) O(1) Optimal performance
For Loop O(n) O(1) Readable code

Conclusion

The mathematical formula (n²) is the most efficient approach for finding the sum of first n odd numbers. For learning purposes, the iterative methods help understand how odd numbers are generated and summed.

Updated on: 2026-03-25T10:56:09+05:30

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements