쉬움 0명 해결 정답률 0%

Difference of Squares

Subtract the sum of squares from the square of the sum.

배우게 될 내용

  • Compute sums of numbers and of squares
  • Use closed formulas instead of loops
  • Compare two ways to get the same answer

문제

번역본 보기

Using the integers from 1 through n, calculate two quantities: first add the integers and square the result; separately square each integer and add those squares. Return the first quantity minus the second.

Implement difference_of_squares(n).

Input

n: The last integer to include.

Output

Return square-of-sum minus sum-of-squares.

제약 조건

0 ≤ n ≤ 50,000. For n = 0, both sums are 0. All required values fit signed 64-bit integers.

예시

예시 1
입력:
n = 4

예상 출력:
expected = 70
입력:
long long n = 4;

예상 출력:
long long expected = 70;
입력:
long n = 4;

예상 출력:
long expected = 70;

설명

(1 + 2 + 3 + 4)² = 100. The sum of squares is 1 + 4 + 9 + 16 = 30. Subtract: 100 − 30 = 70.

예시 2
입력:
n = 1

예상 출력:
expected = 0
입력:
long long n = 1;

예상 출력:
long long expected = 0;
입력:
long n = 1;

예상 출력:
long expected = 0;

설명

Both quantities equal 1, so their difference is 0.

접근 방법

먼저 스스로 풀어 본 뒤 힌트를 하나씩 열어 보세요.

힌트 1

You are comparing two summaries of the same range: one based on summing first, the other based on squaring first.

힌트 2

Use the closed-form expressions for sums of integers and sums of squares instead of looping through every value.

힌트 3

Handle the zero case carefully, since both quantities should be zero there.

예상 복잡도

O(1) time, O(1) extra space

참고 자료

이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.

다른 사람의 풀이 보기

커뮤니티 솔루션

아직 공개된 풀이가 없습니다. 문제를 풀고 첫 풀이를 공유하세요.