[Project Euler Question 6] Sum square difference and sum square difference

Problem 6 Sum square difference

The sum of the squares of the first ten natural numbers is:

1 2 + 2 2 + 3 2 + ⋯ + 1 0 2 = 385 \large 1^2+2^2+3^2+\cdots+10^2=385 12+22+32++102=385

The square of the sum of the first ten natural numbers is:

( 1 + 2 + 3 + ⋯ + 10 ) 2 = 5 5 2 = 3025 \large (1+2+3+\cdots+10)^2=55^2=3025 (1+2+3++10)2=552=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 \large 3025 - 385 = 2640 3025385=2640

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

Question 6 The difference between the sum of squares and the sum of squares

The sum of the squares of the first ten natural numbers is:

1 2 + 2 2 + 3 2 + ⋯ + 1 0 2 = 385 \large 1^2+2^2+3^2+\cdots+10^2=385 12+22+32++102=385

The square of the sum of the first ten natural numbers is:

( 1 + 2 + 3 + ⋯ + 10 ) 2 = 5 5 2 = 3025 \large (1+2+3+\cdots+10)^2=55^2=3025 (1+2+3++10)2=552=3025

Therefore, the difference between the sum of the squares of the first ten natural numbers and the sum of the squares is:

3025 − 385 = 2640 \large 3025 - 385 = 2640 3025385=2640

Find the difference between the sum of the squares of the first one hundred natural numbers and the sum of the squares

Idea analysis

The general formula for the sum of the squares of natural numbers

S ( 1 ) = n ( n + 1 ) ( 2 n + 1 ) 6 \large S(1)=\frac{n(n+1)(2n+1)}{6} S(1)=6n(n+1 ) ( 2 n+1)

Formula for the square general term of the sum of natural numbers

S ( 2 ) = ( n ( n + 1 ) 2 ) 2 \large S(2)=\left ( \frac{n(n+1)}{2} \right )^2 S(2)=(2n(n+1))2

Then the general formula of the square of the sum and the difference of the sum of squares is

S ( n ) = S ( 2 ) − S ( 1 ) = ( n ( n + 1 ) 2 ) 2 − n ( n + 1 ) ( 2 n + 1 ) 6 \large S(n)=S(2)-S(1)=\left ( \frac{n(n+1)}{2} \right )^2-\frac{n(n+1)(2n+1)}{6} S(n)=S(2)S(1)=(2n(n+1))26n(n+1 ) ( 2 n+1)

= n ( n − 1 ) ( n + 1 ) ( 3 n + 2 ) 12 \large =\frac{n(n-1)(n+1)(3n+2)}{12} =12n(n1)(n+1 ) ( 3 n+2)

Code

/*
 * @Author: coder-jason
 * @Date: 2022-04-12 10:48:07
 * @LastEditTime: 2022-04-12 11:16:45
 */
#include <iostream>
using namespace std;

int main()
{
    
    
    int n = 100;
    long long int ans = n * (n - 1) * (n + 1) * (3 * n + 2) / 12;
    cout << ans;
    return 0;
}

Answer: 25164150

Guess you like

Origin blog.csdn.net/m0_51269961/article/details/124118314