1~100의 제곱의 합과 합의 제곱의 차를 구하는 문제입니다.
Sum square difference
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
1~100까지 루프를 돌면서, 하나는 제곱을 해서 더하고, 나머지 하나는 그냥 더한후 제곱을 해서, 마지막에 차이를 계산하면 되겠네요.
1 2 3 4 5 6 7 | total = 0 totalsq = 0 for i in range ( 1 , 101 ): totalsq = totalsq + i * * 2 total = total + i print (totalsq,total,total * * 2 ) print (total * * 2 - totalsq) |
방법2
또는 1번과 비슷하긴 한데, 함수로 나워서 따로 계산해도 되고,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | def get_sq_sum(n): total = 0 for i in range ( 1 , n + 1 ): total = total + pow (i, 2 ) return total def get_sum_sq(n): totalsq = 0 for i in range ( 1 , n + 1 ): totalsq = totalsq + i return pow (totalsq, 2 ) def dif(num): total_1 = get_sq_sum(num) total_2 = get_sum_sq(num) return (total_1 - total_2) print (dif( 100 )) |
방법3
또는
1 2 3 4 5 6 7 8 | import sympy i, n = sympy.symbols( 'i n' ) sum_of_squares = sympy. Sum (i * * 2 , (i, 1 , n)) square_of_sums = sympy. Sum (i, (i, 1 , n)) * * 2 difference = sympy.lambdify(n, square_of_sums - sum_of_squares) print (difference( 100 )) |
sympy 모듈에 있는 기능들을 이용해서 풀수도 있는것 같습니다. 요건 저도 코드를 좀 뜯어보고 업데이트 하도록 하겠습니다.