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.
Example:
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:
Java
// Calculate the Sum of First N Odd & Even Numbers in Java import java.io.*; public class GFG { // Driver function public static void main(String[] args) { int n = 8 ; int evenSum = 0 ; int oddSum = 0 ; for ( int i = 1 ; i <= 2 * n; i++) { // check even & odd using Bitwise AND operator if ((i & 1 ) == 0 ) evenSum += i; else oddSum += i; } // Sum of even numbers less than 17 System.out.println( "Sum of First " + n + " Even numbers = " + evenSum); // sum of odd numbers less than 17 System.out.println( "Sum of First " + n + " Odd numbers = " + oddSum); } } |
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.
Auxiliary Space: O(1)
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:
Java
// Calculate the Sum of First N Odd & Even Numbers in Java import java.io.*; public class GFG { // Function to find the sum of even numbers static int sumOfEvenNums( int n) { return n * (n + 1 ); } // Function to find the sum of odd numbers. static int sumOfOddNums( int n) { return n * n; } // Driver function public static void main(String[] args) { int n = 10 ; int evenSum = sumOfEvenNums(n); int oddSum = sumOfOddNums(n); // Sum of even numbers System.out.println( "Sum of First " + n + " Even numbers = " + evenSum); // sum of odd numbers System.out.println( "Sum of First " + n + " Odd numbers = " + oddSum); } } |
Sum of First 10 Even numbers = 110 Sum of First 10 Odd numbers = 100
Time Complexity: O(1)
Auxiliary Space: O(1)