求第一个 N 奇数和偶数之和的Java程序
当任何以 0、2、4、6、8 结尾的数除以 2 时,即为偶数。而当任何以 1、3、5、7、9 结尾的数不除以二时,就是奇数。
例子:
Input : 8
Output: Sum of First 8 Even numbers = 72
Sum of First 8 Odd numbers = 64
方法#1:迭代
- 创建两个变量 evenSum 和oddSum 并将它们初始化为 0。
- 从 1 到 2*n 开始 For 循环。
- 如果我是 even Add i with evenSum。
- 否则用oddSum添加i。
- 在循环结束时打印evenSum 和oddSum。
下面是Java程序的实现:
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 then 17
System.out.println("Sum of First " + n
+ " Even numbers = " + evenSum);
// sum of odd numbers less then 17
System.out.println("Sum of First " + n
+ " Odd numbers = " + oddSum);
}
}
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 8 Even numbers = 72
Sum of First 8 Odd numbers = 64
时间复杂度: O(N),其中 N 是前 N 个偶数/奇数的数量。
方法 2:使用 AP 公式。
- 前 N 个偶数之和 = n * (n+1)
- 前 N 个奇数之和 = n * n
下面是上述方法的实现:
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
时间复杂度: O(1)