題目6:平方和與和平方的差是多少?

前十個自然數的平方和是:

12 + 22 + ... + 102 = 385

前十個自然數的和的平方是:

(1 + 2 + ... + 10)2 = 552 = 3025

所以平方和與和的平方的差是3025 − 385 = 2640.

找出前一百個自然數的平方和與和平方的差。


暴力算


public class Problem6 {

    public static void main(String[] args) {
        System.out.println(getSumSquare() - getSquareSum());

    }

    private static long getSquareSum() {
        long squareSumRes = 0;

        for (int i = 1; i < 101; i++) {
            squareSumRes += Math.pow(i, 2);
        }

        return squareSumRes;
    }

    private static long getSumSquare() {

        int sum = 0;

        for (int i = 1; i < 101; i++) {
            sum += i;
        }

        return Math.round(Math.pow(sum, 2));
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章