Java程式計算n次方和序列


n次方和序列是一種算術級數的形式,其中平方和按順序排列,首項為1,n為項的總數。

12 + 22 + 32 + ….. + n2

在這篇文章中,我們將討論使用Java程式計算n次方和序列。

方法一:使用迭代方法

讓我們透過一個簡單的例子來理解程式的邏輯。

示例

如果我們將輸入設定為num = 6

它將計算為:1² + 2² + 3² + 4² + 5² + 6² = 1 + 4 + 9 + 16 + 25 + 36 = 91

因此,輸出將為91。

使用For迴圈

For迴圈語法

for (initial expression; conditional expression; increment/decrement expression)
{
   // code to be executed
}

初始表示式 - 迴圈開始時執行一次。

條件表示式 - 當條件表示式為真時,程式碼將被執行。

增量/減量表達式 - 用於增加/減少迴圈變數。

示例

import java.util.*;
public class Main {
   public static void main(String[] args) {
      int addition = 0;
      int num = 6;  
      for(int i = 1; i <= num; i++) {
         addition += i * i; // same as addition = addition + i * i
      }
      System.out.println("Sum of nth series till " + num + "th terms = " + addition);
   }
}

輸出

Sum of nth series till 6th terms = 91

在上面的程式碼中,我們宣告並初始化了兩個名為“num”和“addition”的變數。必須初始化變數,否則編譯器將儲存垃圾值。for迴圈從1執行到“num”的值,並且在每次迭代中,平方和都會儲存在“addition”中。

使用While迴圈

語法

while (conditional expression) 
{
   // code will be executed till conditional expression is true
   increment/decrement expression; 
   // to increment or decrement loop variable
}

示例

import java.util.*;
public class Main {
   public static void main(String[] args) {
      int addition = 0;
      int num = 6;
      int i=0;
      while (i <= num) { 
         // loop is running till 6
         addition += i * i; 
         // to perform sum of squares 
         i++; // incrementing loop variable
      }
      System.out.println("Sum of nth series till " + num + "th terms = " + addition);
   }
}

輸出

Sum of nth series till 6th terms = 91

方法二:使用平方和公式

所有計數數字都稱為自然數。其範圍從1到無窮大。如果我們想找到n個連續自然數的平方和,那麼我們可以在程式中使用給定的公式:

1² + 2² + 3² + ... + num² = ( num * ( num + 1 ) * ( 2 * num + 1 ) ) / 6

讓我們用一個例子來理解這個公式。

示例

如果我們將輸入設定為num = 5

它將計算為:( 5 * ( 5+1 ) * ( 2 * 5 + 1 )) / 6 = ( 5 * 6 * 11 ) / 6 = 330 / 6 = 55

因此,輸出將為55。

示例

import java.util.*;
public class Main {
   public static void main(String[] args) {
      int num = 5;
	   int addition = 0;
      addition = (num * (num + 1) * (2 * num + 1)) / 6; 
      // Using the above Formula
      System.out.println("Sum of nth series till " + num + "th terms = " + addition);
   } 
}

輸出

Sum of nth series till 5th terms = 55

結論

在這篇文章中,我們討論了兩種使用Java程式計算n次方和序列的方法。第一種是使用迭代方法,例如for迴圈或while迴圈;第二種是使用數學公式來計算n個連續自然數的平方和。

更新於:2023年4月25日

瀏覽量:153

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.