
Problem
Solution
Submissions
Implement a Function to Compute the Nth Triangular Number
Certification: Intermediate Level
Accuracy: 50%
Submissions: 2
Points: 5
Write a Python function that calculates the nth triangular number. A triangular number counts the objects that can form an equilateral triangle. The nth triangular number is the sum of the n natural numbers from 1 to n.
Example 1
- Input: 5
- Output: 15
- Explanation:
- Step 1: Take the input number 5.
- Step 2: Calculate the sum of numbers from 1 to 5: 1 + 2 + 3 + 4 + 5 = 15.
- Step 3: Return 15 as the result.
Example 2
- Input: 7
- Output: 28
- Explanation:
- Step 1: Take the input number 7.
- Step 2: Calculate the sum of numbers from 1 to 7: 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.
- Step 3: Return 28 as the result.
Constraints
- 1 ≤ n ≤ 10^4
- Return the triangular number for the given input
- Time Complexity: O(1) using the formula, O(n) using iteration
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- You can use the formula: n*(n+1)/2
- Alternatively, sum the numbers from 1 to n
- Consider using recursion with base case: if n is 1, return 1
- For recursive approach: return n + triangular_number(n-1)