Advertisement
makispaiktis

Project Euler 6 - Sum Square Difference

Apr 25th, 2020 (edited)
645
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.94 KB | None | 0 0
  1. '''
  2. The sum of the squares of the first ten natural numbers is,
  3. 1^2+2^2+...+10^2=385
  4. The square of the sum of the first ten natural numbers is,
  5. (1+2+...+10)^2=55^2=3025
  6. 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.
  7. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
  8. '''
  9.  
  10. def sumOfSquares(n):
  11.     if n != int(n) or n <=0:
  12.         return None
  13.     sum = 0
  14.     for i in range(n):
  15.         sum += (i+1) ** 2
  16.     return sum
  17.  
  18. def squareOfSum(n):
  19.     if n != int(n) or n <=0:
  20.         return None
  21.     sum = 0
  22.     for i in range(n):
  23.         sum += (i+1)
  24.     return sum ** 2
  25.  
  26. # MAIN FUNCTION
  27. N = 100
  28. answer = squareOfSum(N) - sumOfSquares(N)
  29. print("(1 + 2 + 3 + .... + " + str(N-1) + "+ " + str(N) + ")^2 - (1^2 + 2^2 + 3^2 + .... + " + str(N-1) + "^2 + " + str(N) + "^2) = " + str(answer))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement