前 n 個自然數之和的平方與平方之和的差


問題陳述

給定一個數字 n,編寫一個程式來求在前 n 個自然數中平方和與平方之和的差。

舉例說明

n = 3
Squares of first three numbers
= 3x3 + 2x2 + 1x1
= 9 + 4 + 1
= 14

Squares of sum of first three numbers
= (3 + 2 + 1)x(3 + 2 + 1)
= 6x6
= 36

Difference
= 36 - 14
= 22

舉例說明

現場演示

以下是用 Java 編寫的程式,用於查詢所需的差值。

public class JavaTester {
   public static int difference(int n){
      //sum of squares of n natural numbers
      int sumSquareN = (n * (n + 1) * (2 * n + 1)) / 6;
      //sum of n natural numbers
      int sumN = (n * (n + 1)) / 2;
      //square of sum of n natural numbers
      int squareSumN = sumN * sumN;
      //difference
      return Math.abs(sumSquareN - squareSumN);
   }
   public static void main(String args[]){
      int n = 3;
      System.out.println("Number: " + n);
      System.out.println("Difference: " + difference(n));
   }
}

輸出

Number : 3
Difference: 22

更新時間:2020 年 5 月 16 日

857 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.