我看到大多數人只是循環添加數字和他們的正方形。我嘗試了不同的方法。使用小數學,我知道,我意識到我有這是一個非常有效的解決方案:公式「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.議決
你會得到什麼答案? –
你有沒有試圖比較你的數學解決方案和防彈環?另外,'N * N + 1'看起來很可疑 –
因此SO應該有另一個選項來關閉:'User error'。在這種情況下,用戶明顯地放置了'('比這些應該是更早的幾個字符。 – devnull