Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program for Sum of first N even numbers
The sum of the first N even numbers is a mathematical operation where we add up the first N even numbers. In Python, there are multiple ways to calculate this sum. In this article, we will learn various approaches to finding the sum of the first N even numbers in Python.
Understanding the Problem
The first N even numbers form a sequence: 2, 4, 6, 8, 10, ... The mathematical formula for finding their sum is:
Sum = N * (N + 1)
Example: For N=5, the first 5 even numbers are: 2, 4, 6, 8, 10
Sum = 2 + 4 + 6 + 8 + 10 = 30
Using the Direct Formula
This is the most efficient approach using the formula Sum = N * (N + 1) ?
N = 5
sum_even = N * (N + 1)
print(f"The sum of the first {N} even numbers is: {sum_even}")
The sum of the first 5 even numbers is: 30
Time Complexity: O(1)
Using a Loop (Iterative Approach)
This approach uses a loop to iterate and calculate the sum by generating even numbers ?
N = 5
sum_even = 0
for i in range(1, N + 1):
sum_even += 2 * i
print(f"The sum of the first {N} even numbers is: {sum_even}")
The sum of the first 5 even numbers is: 30
Time Complexity: O(N)
Using List Comprehension
Python provides a concise way using list comprehensions with the built-in sum() function ?
N = 5
sum_even = sum([2 * i for i in range(1, N + 1)])
print(f"The sum of the first {N} even numbers is: {sum_even}")
The sum of the first 5 even numbers is: 30
Time Complexity: O(N)
Using a Reusable Function
Creating a function makes the code modular and reusable ?
def sum_even_numbers(N):
return N * (N + 1)
# Test the function
N = 5
result = sum_even_numbers(N)
print(f"The sum of the first {N} even numbers is: {result}")
# Test with different values
for n in [3, 7, 10]:
print(f"N={n}: Sum = {sum_even_numbers(n)}")
The sum of the first 5 even numbers is: 30 N=3: Sum = 12 N=7: Sum = 56 N=10: Sum = 110
Comparison of Methods
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Direct Formula | O(1) | O(1) | Maximum efficiency |
| Loop | O(N) | O(1) | Understanding the logic |
| List Comprehension | O(N) | O(N) | Pythonic code style |
| Function | O(1) | O(1) | Reusability |
Conclusion
The direct formula method N * (N + 1) is the most efficient with O(1) time complexity. Use the loop-based approach for educational purposes and list comprehension for Pythonic style, though both have O(N) complexity.
