Triangular Number Series - Problem

Given a positive integer n, generate the first n triangular numbers.

A triangular number is the sum of all natural numbers up to a given position. The sequence starts as: 1, 3, 6, 10, 15, 21, 28, ...

For example:

  • 1st triangular number: 1 (sum of 1)
  • 2nd triangular number: 3 (sum of 1+2)
  • 3rd triangular number: 6 (sum of 1+2+3)
  • 4th triangular number: 10 (sum of 1+2+3+4)

Return the result as an array of integers.

Input & Output

Example 1 — First 5 Triangular Numbers
$ Input: n = 5
Output: [1, 3, 6, 10, 15]
💡 Note: T₁=1, T₂=1+2=3, T₃=1+2+3=6, T₄=1+2+3+4=10, T₅=1+2+3+4+5=15
Example 2 — First 3 Triangular Numbers
$ Input: n = 3
Output: [1, 3, 6]
💡 Note: First triangular: 1, second: 1+2=3, third: 1+2+3=6
Example 3 — Edge Case Single Number
$ Input: n = 1
Output: [1]
💡 Note: Only the first triangular number, which is 1

Constraints

  • 1 ≤ n ≤ 1000
  • Result fits in 32-bit integer

Visualization

Tap to expand
Triangular Number Series - Mathematical ApproachINPUTn = 4Need first 4 triangular numbersT₁1T₂1+2T₃1+2+3T₄1+2+3+4Generate sequence:[T₁, T₂, T₃, T₄]ALGORITHMFormula: T(k) = k×(k+1)/2Direct calculation1T₁ = 1×2/2 = 12T₂ = 2×3/2 = 33T₃ = 3×4/2 = 64T₄ = 4×5/2 = 10Time: O(n) - Single loopSpace: O(n) - Result arrayNo nested loops needed!Mathematical eleganceRESULTTriangular Array:13610[1, 3, 6, 10]Complete seriesgenerated instantlyKey Insight:The mathematical formula T(k) = k×(k+1)/2 eliminates the need for nested loopsor accumulation, providing instant calculation of any triangular number.TutorialsPoint - Triangular Number Series | Mathematical Formula Approach
Asked in
Google 25 Microsoft 18 Amazon 15
23.4K Views
Medium Frequency
~12 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen