gpt4 book ai didi

java - 平方和差 - 我的方法有什么问题?

转载 作者:行者123 更新时间:2023-12-01 17:22:36 25 4
gpt4 key购买 nike

我发现大多数人只是循环添加数字及其平方。我尝试了一种不同的方法。利用我所知的一点数学知识,我意识到我有一个非常有效的解决方案:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com