Sum of First N Even Numbers in Python
The sum of the first N even numbers is a mathematical operation. In this operation, we add up the firstN even numbers. In Python, there are multiple ways to calculate this sum. In this article, we are going to learn and discuss various approaches to finding the sum of the first N even numbers in Python.
Finding the Sum of the First N Even Numbers
The formula for finding the sum of the first N even numbers is:
Sum = N * (N + 1)
Example 1
Let's look at a scenario where N=5, The first 5 even numbers are: 2, 4, 6, 8, 10. then the sum would be Sum = 2 + 4 + 6 + 8 + 10 = 30.
Input: N=5
Output: 30
Using the Formula
This is the simple and direct approach for finding the sum of the first N even numbers. In this approach, we use the formula Sum = N * (N + 1) to calculate the result.
Example
N = 5 sum_even = N * (N + 1) print(f"The sum of the first {N} even numbers is: {sum_even}")
Output
The sum of the first 5 even numbers is: 30Time Complexity
O(1)
Using a Loop (Iterative Approach)
In this approach, we use a loop to calculate the sum of the first N even numbers by iterating from 1 to N and multiplying each index by 2.
Example
numberN = 5 sum_even = 0 for i in range(1, numberN + 1): sum_even += 2 * i print(f"The sum of the first {numberN} even numbers is: {sum_even}")
Output
The sum of the first 5 even numbers is: 30Time Complexity
O(N)
Using List Comprehension and sum() Function
Python provides a powerful way to generate sequences and calculate sums using list comprehensions and the built-in sum() function.
Example
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}")
Output
The sum of the first 5 even numbers is: 30Time Complexity
O(N)
Using a Function
This approach allows us to define a function that accepts a number as an argument and returns the sum of the first N even numbers. This makes the code reusable and modular.
Example
def sum_even_numbers(N): return sum([2 * i for i in range(1, N + 1)]) N = 5 sum_even = sum_even_numbers(N) print(f"The sum of the first {N} even numbers is: {sum_even}")
Output
The sum of the first 5 even numbers is: 30Time Complexity
O(N)
Conclusion
In this article, we discussed multiple ways to calculate the sum of the first N even numbers in Python. The direct formula method is the most efficient with O(1) time complexity. The loop-based approach is straightforward but takes O(N) time. Using list comprehension makes the code more Pythonic, while defining a function improves reusability.
By understanding these different approaches, you can choose the one that best suits your needs based on efficiency and readability.