Java Program to Find the Sum of First N Odd & Even Numbers
Last Updated :
19 Oct, 2022
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
import java.io.*;
public class GFG {
public static void main(String[] args)
{
int n = 8 ;
int evenSum = 0 ;
int oddSum = 0 ;
for ( int i = 1 ; i <= 2 * n; i++) {
if ((i & 1 ) == 0 )
evenSum += i;
else
oddSum += i;
}
System.out.println( "Sum of First " + n
+ " Even numbers = " + evenSum);
System.out.println( "Sum of First " + n
+ " Odd numbers = " + oddSum);
}
}
|
Output
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
import java.io.*;
public class GFG {
static int sumOfEvenNums( int n) { return n * (n + 1 ); }
static int sumOfOddNums( int n) { return n * n; }
public static void main(String[] args)
{
int n = 10 ;
int evenSum = sumOfEvenNums(n);
int oddSum = sumOfOddNums(n);
System.out.println( "Sum of First " + n
+ " Even numbers = " + evenSum);
System.out.println( "Sum of First " + n
+ " Odd numbers = " + oddSum);
}
}
|
Output
Sum of First 10 Even numbers = 110
Sum of First 10 Odd numbers = 100
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...