Dễ 0 đã giải Tỷ lệ chấp nhận 0%

Difference of Squares

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

Bạn sẽ học được gì

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

Đề bài

Xem bản dịch

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.

Ràng buộc

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

Ví dụ

Ví dụ 1
Đầu vào:
n = 4

Kết quả mong đợi:
expected = 70
Đầu vào:
long long n = 4;

Kết quả mong đợi:
long long expected = 70;
Đầu vào:
long n = 4;

Kết quả mong đợi:
long expected = 70;

Giải thích

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

Ví dụ 2
Đầu vào:
n = 1

Kết quả mong đợi:
expected = 0
Đầu vào:
long long n = 1;

Kết quả mong đợi:
long long expected = 0;
Đầu vào:
long n = 1;

Kết quả mong đợi:
long expected = 0;

Giải thích

Both quantities equal 1, so their difference is 0.

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

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

Gợi ý 2

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

Gợi ý 3

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

Độ phức tạp mong đợi

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

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Học hỏi từ người khác

Giải pháp cộng đồng

Chưa có giải pháp nào được chia sẻ. Hãy giải thử thách này để đăng giải pháp đầu tiên.