Java 显示前N个自然数及其和
自然数是指范围在1到正无穷的所有正整数或整数。在本文中,我们将看到如何在Java中显示数字以及前N个自然数的和,其中N由用户定义。从数学上讲,前N个自然数的和由公式给出−
总和 = n * (n+1) / 2
为了在Java中实现此功能,主要有三种方法略有不同。
1. 使用for循环或do-while循环或while循环
这里的方法很简单。我们从用户输入获取一个值来确定n的值。变量sum初始化为0。然后,我们运行一个从1到n的for循环。在每次迭代中,打印循环变量的值并将其加到sum变量中。循环结束后,我们打印sum的值。
在此方法中, 时间复杂度为O(n) 其中n是要执行所有计算的自然数。原因是循环运行n次以计算和并打印前n个自然数。
示例
public class Main {
public static void main(String[] args) {
int n = 5; // stores the value of n that user inputs
int sum = 0; //stores the sum
System.out.print("The first " + n + " natural numbers are:");
for (int i = 1; i <= n; i++) {
/* For loop goes from 1 to n, prints each number during the iteration and keeps adding it to the sum variable */
System.out.print(i + " ");
sum += i;
}
System.out.println("");
System.out.println("\n The sum of the first " + n + " natural numbers is: " + sum); //print the sum
}
}
输出
上面的程序将产生以下输出 –
The first 5 natural numbers are:1 2 3 4 5
The sum of the first 5 natural numbers is: 15
2. 使用数学公式
这种方法与上面的方法非常相似,只是有一个小的差异,可以得到相对更高的准确性。在迭代过程中,我们不再重复地将数字添加到总和中,而是在循环中仅打印自然数,而总和在循环之前使用以下公式计算: SUM = N * (N+1)/2
在这种方法中, 时间复杂度为O(1) ,因为程序通过上述公式计算前n个自然数的总和。这需要一个恒定的时间量,无论n的值如何。然而,由于程序使用for循环来显示数字并运行n次,因此 程序的总体时间复杂度仍然是O(n)
示例
public class Main {
public static void main(String[] args) {
int n = 5; // stores the value of n that user
int sum = (n * (n + 1)) / 2; // calculate the sum using formula method
System.out.print("The first " + n + " natural numbers are:");
for (int i = 1; i <= n; i++) {
/* For loop goes from 1 to n, prints each number during the iteration */
System.out.print(i + " ");
}
System.out.println(" ");
System.out.println("\nThe sum of the first " + n + " natural numbers is: " + sum); //print the sum
}
}
输出
上述程序将产生以下输出 –
The first 5 natural numbers are:1 2 3 4 5
The sum of the first 5 natural numbers is: 15
3. 使用递归
这里的方法是,一个用户定义的函数sumOfNaturals(int n)递归地调用自身,直到递归的基础条件被满足为止。这里的基础条件是当n等于1时。如果没有达到基础条件,函数返回n +调用sumOfNaturals(n-1)的结果的函数调用。for循环负责打印数字。
这里的时间复杂度为O(n),其中n对应要显示和求和的自然数。原因是函数sumofNaturals(n)对于从n到1的每个n值执行一次加法运算和一次函数调用。因此,执行的操作次数与n成正比。
示例
public class Main {
public static int sumOfNaturals(int n) {
if (n == 1) {
return 1;
}
return n + sumOfNaturals(n-1);
}
public static void main(String[] args) {
int n = 5;
int sum = sumOfNaturals(n);
System.out.print("The first " + n + " natural numbers are: ");
for (int i = 1; i <= n; i++) {
System.out.print(i + " ");
}
System.out.println();
System.out.println("\nThe sum of the first " + n + " natural numbers is: " + sum);
}
}
输出
上述程序将生成以下输出 –
The first 5 natural numbers are: 1 2 3 4 5
The sum of the first 5 natural numbers is: 15
结论
在Java中编写一个程序以同时显示前n个自然数并计算它们的和,对于那些学习Java的人来说是一个很好的起点。这里演示了基本概念,如循环、执行算术运算和递归。第一种方法使用一个一直循环来显示和计算总和。第二种方法使用数学公式来计算总和,并使用for循环来打印所有的数字。第三种方法使用迭代来计算总和,而其余部分保持不变。
所有方法的时间复杂度都是线性的。第一种方法的求和和显示都是O(n),第二种方法的求和是O(1),但显示数字是O(n)。第三种方法的打印和计算都是O(n),总体上是O(n)。