1 | """ |
||
2 | Project Euler Problem 6: Sum Square Difference |
||
3 | ============================================== |
||
4 | |||
5 | .. module:: solutions.problem6 |
||
6 | :synopsis: My solution to problem #6. |
||
7 | |||
8 | The source code for this problem can be |
||
9 | `found here <https://bitbucket.org/nekedome/project-euler/src/master/solutions/problem6.py>`_. |
||
10 | |||
11 | Problem Statement |
||
12 | ################# |
||
13 | |||
14 | The sum of the squares of the first ten natural numbers is, |
||
15 | :math:`1^2 + 2^2 + \\dots + 10^2 = 385` |
||
16 | |||
17 | The square of the sum of the first ten natural numbers is, |
||
18 | :math:`(1 + 2 + \\dots + 10)^2 = 55^2 = 3025` |
||
19 | |||
20 | Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is |
||
0 ignored issues
–
show
|
|||
21 | :math:`3025 - 385 = 2640`. |
||
22 | |||
23 | Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. |
||
0 ignored issues
–
show
|
|||
24 | |||
25 | Solution Discussion |
||
26 | ################### |
||
27 | |||
28 | Simply iteratively build and sum the components of the two sequences: |
||
29 | |||
30 | * sum of the squares |
||
31 | * square of the sums |
||
32 | |||
33 | for the natural numbers :math:`1,2,\\dots,100` |
||
34 | |||
35 | Return the absolute value of the difference of these two sums. |
||
36 | |||
37 | Solution Implementation |
||
38 | ####################### |
||
39 | |||
40 | .. literalinclude:: ../../solutions/problem6.py |
||
41 | :language: python |
||
42 | :lines: 45- |
||
43 | """ |
||
44 | |||
45 | from math import fabs |
||
46 | |||
47 | |||
48 | def solve(): |
||
49 | """ Compute the answer to Project Euler's problem #6 """ |
||
50 | upper_bound = 100 |
||
51 | sum_of_squares = 0 |
||
52 | square_of_sums = 0 |
||
53 | for i in range(1, upper_bound + 1): |
||
54 | sum_of_squares += i * i |
||
55 | square_of_sums += i |
||
56 | square_of_sums = square_of_sums * square_of_sums |
||
57 | answer = int(fabs(square_of_sums - sum_of_squares)) |
||
58 | return answer |
||
59 | |||
60 | |||
61 | expected_answer = 25164150 |
||
0 ignored issues
–
show
The name
expected_answer does not conform to the constant naming conventions ((([A-Z_][A-Z0-9_]*)|(__.*__))$ ).
This check looks for invalid names for a range of different identifiers. You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements. If your project includes a Pylint configuration file, the settings contained in that file take precedence. To find out more about Pylint, please refer to their site. ![]() |
|||
62 |
This check looks for lines that are too long. You can specify the maximum line length.