ง่าย 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

Triangular Number

Add the integers from 1 through n.

สิ่งที่คุณจะได้เรียนรู้

  • Add the numbers from 1 to n with a loop
  • Learn the formula n × (n + 1) / 2
  • Compare a loop with a constant-time formula

โจทย์

ดูฉบับแปล

The n-th triangular number is 1 + 2 + … + n. A formula avoids looping over huge inputs. The 0th triangular number is 0.

Implement triangular_number(n).

Input

n: A non-negative integer.

Output

Return 1 + 2 + … + n.

เงื่อนไข

0 ≤ n ≤ 1,000,000,000. The result fits a signed 64-bit integer.

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
n = 10

ผลลัพธ์ที่คาดหวัง:
expected = 55
อินพุต:
long long n = 10;

ผลลัพธ์ที่คาดหวัง:
long long expected = 55;
อินพุต:
long n = 10;

ผลลัพธ์ที่คาดหวัง:
long expected = 55;

คำอธิบาย

1 + 2 + … + 10 = 55.

ตัวอย่างที่ 2
อินพุต:
n = 0

ผลลัพธ์ที่คาดหวัง:
expected = 0
อินพุต:
long long n = 0;

ผลลัพธ์ที่คาดหวัง:
long long expected = 0;
อินพุต:
long n = 0;

ผลลัพธ์ที่คาดหวัง:
long expected = 0;

คำอธิบาย

No numbers to add, so the sum is 0.

แนวทางการแก้

ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ

คำใบ้ 1

Look for a pattern in the running totals instead of adding every number one by one.

คำใบ้ 2

Use the arithmetic-series shortcut based on the first and last terms, which avoids looping.

คำใบ้ 3

Be careful with the 0 case, and ensure your arithmetic stays within 64-bit limits.

ความซับซ้อนที่คาดหวัง

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

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

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

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

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

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