In Java, numbers that are divisible by 2 are called even numbers (ending with 0, 2, 4, 6, 8), while numbers that are not divisible by 2 are called odd numbers (ending with 1, 3, 5, 7, 9).
In this article, we will learn how to calculate the sum of the first N even numbers and the first N odd numbers using two simple approaches.
Example:
Input : 8
Output:Sum of First 8 Even numbers = 72
Sum of First 8 Odd numbers = 64
Approach 1: Iterative Method
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);
}
}
Explanation:
- The variable n defines how many even and odd numbers are needed.
- A loop runs from 1 to 2*n to cover both odd and even numbers.
- The bitwise AND operator & is used to check whether a number is even or odd.
- Even numbers are added to evenSum and odd numbers to oddSum.
- Time Complexity: O(N) and Auxiliary Space: O(1)
Approach 2: Using Arithmetic Progression (AP) Formulas
Mathematical Formulas
- Sum of first N even numbers: N × (N + 1)
- Sum of first N odd numbers: N × N
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);
}
}
Try It Yourself
Output
Sum of First 10 Even numbers = 110 Sum of First 10 Odd numbers = 100
Explanation:
- Two helper methods are defined to compute sums using formulas instead of loops.
- Time Complexity: O(1) and Auxiliary Space: O(1)