आसान 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

हर कोडर का सबसे अच्छा पास हुआ समाधान। तेज़, कम मेमोरी वाले और बेहतर रेटिंग वाले समाधान ऊपर रहते हैं।

अभी कोई पास हुआ समाधान नहीं है। इसे हल करें और पहला स्थान पाएँ।

दूसरों से सीखें

समुदाय समाधान

अभी तक कोई प्रकाशित समाधान नहीं। पहला साझा करने के लिए इस चुनौती को हल करें।