Problem 6 - Project Euler
The page has been left unattended for too long and that link/button is no longer active. Please refresh the page.
projecteuler.net
문제는 다음과 같습니다.
The sum of the squares of the first ten natural numbers is,
12+22+...+102=385
The square of the sum of the first ten natural numbers is,
(1+2+...+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.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
1에서 10까지의 각 요소들을 제곱한 것의 합(385)과 각 요소들의 합에 제곱을 한 값(3025)의 차이는 3025-385=2640입니다. 1에서 100까지일 경우의 결과값을 얼마인가? 입니다.
이 문제는 자연수・거듭제곱의 합공식을 이용하여 구했습니다. 참조한 사이트는 아래와 같습니다. 둘 다 거듭제곱의 합공식을 이끌어내는 것을 다루고 있는 내용이지만, 서로 다른 방식으로 증명했기 때문에 읽어보면 재미있을 것이라 생각합니다.
trans4mind.com/personal_development/mathematics/series/sumNaturalSquares.htm
결론적으로 공식만을 적어보면 아래와 같습니다.
자연수의 합의 제곱 : ( ( n * ( n + 1 ) ) / 2 ) ^ 2
제곱의 합 : ( n * ( n + 1 ) * ( ( 2 * n ) + 1 ) ) / 6
위의 공식들을 이용하여 작성한 코드는 아래와 같습니다.
# the sum of the squares calc is ref below site
# https://trans4mind.com/personal_development/mathematics/series/sumNaturalSquares.htm
# https://mathbang.net/628
# the sum of the squares formula
# ( n * ( n + 1) * ( ( 2 * n ) + 1) ) / 6
# the square of the sum formula
# ( ( n * ( n + 1) ) / 2 ) ^ 2
import math
def calcSumOfSquare(n) :
return ( n * ( n + 1) * ( ( 2 * n ) + 1) ) / 6
def calcSquareOfSum(n) :
return math.pow( ( n * ( n + 1) ) / 2 , 2)
n1 = calcSumOfSquare(100)
n2 = calcSquareOfSum(100)
print(n2-n1)
'알고리즘 > Project Euler' 카테고리의 다른 글
8. Largest product in a series (0) | 2020.10.28 |
---|---|
7. 10001st prime (0) | 2020.10.23 |
5. Smallest multiple (0) | 2020.10.12 |
4. Largest palindrome product (0) | 2020.10.08 |
3. Largest prime factor (0) | 2020.10.07 |