簡體   English   中英

平方差總和-我的方法有什么問題?

[英]Sum square difference - What's wrong with my approach?

我看到大多數人只是四處循環以添加數字和平方。 我嘗試了另一種方法。 使用我所知道的小數學,我意識到我有一個非常有效的解決方案:

public static long sumOfNSquares(int N){
   // This is the standard mathematical formula I learnt in grade 10
    return (long) (N*(N+1)*(2*N+1))/6;
}
public static long squareofSum(int N){
   // Another standard mathematical formula. I took a square of it
    return (long) Math.pow( (N * N+1) /2, 2);
}

public static void main(String [] args){
    System.out.println(Math.abs(sumOfNSquares(100) - squareofSum(100)));
}

這使用標准的“ N個自然數之和”和“ N個數的平方和”公式。 仍然我得到錯誤的答案。 可能是什么問題?

ps已解決

使用此Math.pow( (N * (N+1)) /2, 2)

N+1周圍使用花括號

您的N*N+1看起來不對。 *運算符的優先級高於+運算符,因此它將等於(N*N)+1 所以用N*(N+1)

你需要

public static long squareofSum(int N){
    // Another standard mathematical formula. I took a square of it
    return (long) Math.pow( (N * (N+1)) /2, 2);
}

這是支持測試驅動開發的典型案例。 通過這種方法運行一些明顯的測試用例,當那些數學錯別字滲入您的代碼時,您將節省很多時間,因為它們是不會做的。

高斯是系列的開創者,他沉迷於計算示例。 也許是這樣的問題從小就將這種習慣灌輸給他。

您必須使用方括號()對操作進行分組

return (long) Math.pow( (N * (N+1)) /2, 2);

因為,在Java中*優先於+,因此如果沒有方括號,則將首先評估N * N。 但是期望的是要評估的N *(N + 1)。

import java.util.*;

public class soq {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        long N = input.nextLong();

        while (N > 2) {
            long sumSquares = 0, sum = 0, difference = 0;

            for (int i = 1; i <= N; i++) {

                sum += i;

                sumSquares +=  Math.pow(i, 2);

            }

            difference =  (long) (Math.pow(sum, 2) - sumSquares);

            System.out.println(difference);

            N = input.nextInt();
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM