我发现大多数人只是循环添加数字及其平方。我尝试了一种不同的方法。利用我所知的一点数学知识,我意识到我有一个非常有效的解决方案:
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 个数字的平方和”公式。我仍然得到错误的答案。可能出了什么问题?
附:已解决
最佳答案
使用这个Math.pow( (N * (N+1))/2, 2)
在N+1
周围使用大括号
关于java - 平方和差 - 我的方法有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17487616/