TheAlgorithms-Python
41 строка · 1021.0 Байт
1"""
2Project Euler Problem 6: https://projecteuler.net/problem=6
3
4Sum square difference
5
6The sum of the squares of the first ten natural numbers is,
71^2 + 2^2 + ... + 10^2 = 385
8
9The square of the sum of the first ten natural numbers is,
10(1 + 2 + ... + 10)^2 = 55^2 = 3025
11
12Hence the difference between the sum of the squares of the first ten
13natural numbers and the square of the sum is 3025 - 385 = 2640.
14
15Find the difference between the sum of the squares of the first one
16hundred natural numbers and the square of the sum.
17"""
18
19
20def solution(n: int = 100) -> int:
21"""
22Returns the difference between the sum of the squares of the first n
23natural numbers and the square of the sum.
24
25>>> solution(10)
262640
27>>> solution(15)
2813160
29>>> solution(20)
3041230
31>>> solution(50)
321582700
33"""
34
35sum_cubes = (n * (n + 1) // 2) ** 2
36sum_squares = n * (n + 1) * (2 * n + 1) // 6
37return sum_cubes - sum_squares
38
39
40if __name__ == "__main__":
41print(f"{solution() = }")
42