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

Triangular Number

Add the integers from 1 through n.

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

  • 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

Đề bài

Xem bản dịch

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.

Ràng buộc

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

Ví dụ

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

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

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

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

Giải thích

1 + 2 + … + 10 = 55.

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

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

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

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

Giải thích

No numbers to add, so the sum 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

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

Gợi ý 2

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

Gợi ý 3

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

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

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

Lời giải đạt tốt nhất của mỗi người. Lời giải nhanh hơn, tốn ít bộ nhớ hơn và được đánh giá cao hơn sẽ đứng trên.

Chưa có lời giải nào đạt. Giải bài này để giành hạng nhất.

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.