Java程序显示数字和前N个自然数的和
自然数是所有正整数或整数,范围从1到无穷大。在本文中,我们将了解如何在Java中找到前N个自然数的和,其中N是需要从1开始将所有数字相加的整数。
示例场景
Input: num = 5 Output: sum = 15
sum = 1 + 2 + 3 + 4 + 5
使用for循环
在这种方法中,初始化一个值为0的变量来存储和。然后,运行一个for循环,该循环从1到给定数字。在每次迭代中,打印循环变量的值,并将该值加起来以获得总和。循环终止后,打印总和。
时间复杂度将为O(n),其中n是需要执行所有计算的自然数。其原因在于循环运行n次以计算总和并打印前n个自然数。
示例
以下Java程序展示了如何使用for循环查找前N个自然数的和。
public class Main {
public static void main(String[] args) {
// stores the value of n that user inputs
int n = 5;
//stores the sum
int sum = 0;
System.out.print("The first " + n + " natural numbers are: ");
/* For loop goes from 1 to n, prints each number during the
iteration and keeps adding it to the sum variable */
for (int i = 1; i <= n; i++) {
System.out.print(i + " ");
sum += i;
}
//print the sum
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
使用数学公式
该方法与上述方法非常相似,只是有一点细微的差别,导致相对更高的准确性。我们不会在迭代期间重复添加数字,而是使用数学公式计算总和。
查找前N个自然数和的数学公式为:
Sum = N * (N+1)/2
这里,时间复杂度将为O(1),因为程序将花费恒定的时间,而不管n的值是多少。但是,程序的整体时间复杂度仍然为O(n),因为程序使用for循环来显示数字,并且运行n次。
示例
让我们看看上述方法的实际演示:
public class Main {
public static void main(String[] args) {
// stores the value of n that user
int n = 8;
// calculate the sum using formula
int sum = (n * (n + 1)) / 2;
System.out.print("The first " + n + " natural numbers are: ");
/* For loop goes from 1 to n, prints each number
during the iteration */
for (int i = 1; i <= n; i++) {
System.out.print(i + " ");
}
//print the sum
System.out.println("\nThe sum of the first " + n + " natural numbers is: " + sum);
}
}
以上程序将产生以下输出:
The first 8 natural numbers are: 1 2 3 4 5 6 7 8 The sum of the first 8 natural numbers is: 36
使用递归
创建一个用户定义的函数,该函数递归调用自身,直到达到递归的基线。这里的基线是当给定数字等于1时。如果未达到基线,则此函数将继续添加所有自然数,直到给定数字。
这里的时间复杂度为O(n),其中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("\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
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP