Tutorialspoint
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)
ArraysRecursioneBayDropbox
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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)

Steps to solve by this approach:

 Step 1: Understand the triangular number concept (sum of first n natural numbers)

 Step 2: Apply the mathematical formula: n * (n + 1) / 2
 Step 3: Use integer division (//) to ensure the result is an integer
 Step 4: Calculate n * (n + 1) first
 Step 5: Divide the product by 2 using integer division
 Step 6: Return the calculated triangular number  
 Step 7: Example: triangular_number(5) = (5 * 6) / 2 = 15

Submitted Code :