算法3:前n个自然数的平方和与和的平方之间的差

已知:* The sum of the squares of the first ten natural numbers is,
* 1^2+2^2+...+10^2=385
* The square of the sum of the first ten natural numbers is,
* (1+2+...+10)^2=55^2=3025
* Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025−385=2640.
求: * Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. 25502500-338350=25164150

    public static int findDiff(int in_num) {
        int num1 = 0;
        int num2 = 0;
        for (int i = 1; i <= in_num; i++) {
            num1 += (i * i);
            num2 += i;
        }
        System.out.println("num1 = " + num1 + "\nnum2 = " + num2 * num2 + "\ndiff = " + (num2 * num2 - num1));
        return num2 * num2 - num1;
    }

  

posted @ 2020-06-23 17:21  BORS  阅读(269)  评论(0编辑  收藏  举报
bors