2013-07-05 52 views
0

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

我看到大多數人只是循環添加數字和他們的正方形。我嘗試了不同的方法。使用小數學,我知道,我意識到我有這是一個非常有效的解決方案:公式「N數字的平方和」

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自然數之和」和。仍然我得到錯誤的答案。什麼可能是錯的?

p.s.議決

+0

你會得到什麼答案? –

+2

你有沒有試圖比較你的數學解決方案和防彈環?另外,'N * N + 1'看起來很可疑 –

+0

因此SO應該有另一個選項來關閉:'User error'。在這種情況下,用戶明顯地放置了'('比這些應該是更早的幾個字符。 – devnull

回答

4

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

使用大括號圍繞N+1

+0

非常感謝!真的很差的錯誤... – Aditya

0

你需要

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); 
} 

這有利於測試驅動開發的一個典型案例。通過這種方法運行一些明顯的測試用例,當那些數學拼寫錯誤進入你的代碼時,你將會節省很多時間,因爲他們不願意這樣做。

高斯是系列的先驅,他沉迷於計算例子。也許是這樣的問題,從小就把習慣灌輸給他。

1

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

0

你必須用括號()到組的操作

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

因爲,在Java *擁有超過+更大的優先權,因此如果沒有括號則N * N先求。但是,預計會有N *(N + 1)被評估。

+0

其實,第一個支架是不必要的。公式是n * (n + 1)*(2n + 1)/ 6. –

+0

對不起,我錯過了它 – MohamedSanaulla

+1

感謝羅布指出它,我已經改變了我的答案 – MohamedSanaulla

0
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(); 
     } 
    } 
} 
+0

這是正確的,但th e法官考慮時間限制exc我可以做些什麼來讓它更快更快 – jack

+0

你的意思是你寫的是什麼? – jack

+0

夥計我很抱歉,但我不明白 – jack