top of page

Project Euler Problem 6: Sum Square Difference in Python
6 days ago
1 min read
0
0
0

Found the difference between the sum of squares and the square of sums for the first 100 natural numbers.
The problem: Calculate (1² + 2² + ... + 100²) vs (1 + 2 + ... + 100)²
python
sum_of_squares = []
sum_of_numbers = []
for i in range(0,101):
sum_of_squares.append(i*i)
sum_of_numbers.append(i)
ss = sum(sum_of_squares)
sn = sum(sum_of_numbers)
sn2 = sn * sn
print(abs(ss - sn2))Result: 25,164,150
The mathematical elegance here is that while both operations use the same numbers, the order of operations creates a massive difference. Squaring individual numbers before summing gives a much smaller result than summing first, then squaring the total.
Python's list comprehension and built-in sum() function make this straightforward to implement and easy to verify.
Related Posts
Comments
Share Your ThoughtsBe the first to write a comment.
bottom of page





