Given a number N which represents the last term of the Triangle Pattern. The task is to print the Triangle Pattern from 1 to N, such that each row is complete.
Triangle Pattern is given as:
1 2 3 4 5 6 7 8 9 10 . .
Input: N = 3 Output: 1 2 3 Input: N = 7 Output: 1 2 3 4 5 6 7 will not be printed as it would result in an incomplete row
- Find the number of complete rows from the given last term N.
For Max Height = 1, the last term would be 1
For Max Height = 2, the last term would be 3
For Max Height = 3, the last term would be 6
- So the last term forms a pattern: 1, 3, 6, 10, 15,…
- Therefore, the n-th term of series 1, 3, 6, 10, 15,…
A(n) = 1 + 2 + 3 + 4… + (n – 1) + n
= n(n + 1) / 2
i.e A(n) is the sum of First n natural numbers.
- So in
A(n) = n(n + 1) / 2 A(n) represents the last term (as per our problem), and n represents the max height of the Triangle
- Hence this can be seen as:
Last term = height (height + 1) / 2
height = (-1 + sqrt(1 + 8*lastTerm)) / 2
- After finding the max height, the triangle pattern can be easily printed.
Below is the implementation of the above approach:
1 2 3 4 5 6
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Printing Triangle Pattern in Java
- Printing triangle star pattern using a single loop
- Inner reducing pattern printing
- Printing Heart Pattern in C
- How to learn Pattern printing easily?
- Printing string in plus ‘+’ pattern in the matrix
- Program for Expressionless Face Pattern printing
- Pattern Printing question asked in CGI Coding Round
- Print Triangle separated pattern
- Print symmetric double triangle pattern
- Program to print hollow Triangle pattern
- Program for incrementing/decrementing triangle pattern
- Program to print modified Binary triangle pattern
- Nth term where K+1th term is product of Kth term with difference of max and min digit of Kth term
- Nth term of a sequence formed by sum of current term with product of its largest and smallest digit
- Count sequences of length K having each term divisible by its preceding term
- Find Nth term of the series where each term differs by 6 and 2 alternately
- Find the Nth term of the series where each term f[i] = f[i - 1] - f[i - 2]
- Sum of series till N-th term whose i-th term is i^k - (i-1)^k
- Biggest Reuleaux Triangle within a Square which is inscribed within a Right angle Triangle
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.