When any number which ends with 0,2,4,6,8 is divided by 2 that is an even number. And when any number ends with 1,3,5,7,9 is not divided by two is an odd number.
Input : 8 Output: Sum of First 8 Even numbers = 72 Sum of First 8 Odd numbers = 64
Approach #1: Iterative
- Create two variables evenSum and oddSum and initialize them by 0.
- Start For loop from 1 to 2*n.
- If i is even Add i with evenSum.
- Else add i with oddSum.
- Print evenSum and oddSum at the end of loop.
Below is the implementation of the Java program:
Sum of First 8 Even numbers = 72 Sum of First 8 Odd numbers = 64
Time Complexity: O(N), where N is the number of First N even/odd numbers.
Method 2: Using AP Formulas.
- Sum of First N Even Numbers = n * (n+1)
- Sum of First N Odd Numbers = n * n
Below is the implementation of the above approach:
Sum of First 10 Even numbers = 110 Sum of First 10 Odd numbers = 100
Time Complexity: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.