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
廣告