ง่าย 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 กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

คำตอบที่ผ่านดีที่สุดของแต่ละคน คำตอบที่เร็วกว่า ใช้หน่วยความจำน้อยกว่า และได้คะแนนดีกว่าจะอยู่ด้านบน

ยังไม่มีคำตอบที่ผ่าน แก้โจทย์นี้แล้วคว้าอันดับหนึ่งไปเลย

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก