![]() |
VOOZH | about |
A triangular number or triangle number counts objects arranged in an equilateral triangle, as in the diagram on the right. The n-th triangular number is the number of dots composing a triangle with n dots on a side, and is equal to the sum of the n natural numbers from 1 to n.
Examples :
Input : 5 Output : 1 3 6 10 15 Input : 10 Output : 1 3 6 10 15 21 28 36 45 55 Explanation : For k = 1 and j = 1 -> print k ( i.e. 1); increase j by 1 and add into k then print k ( i.e 3 ) update k increase j by 1 and add into k then print k ( i.e 6 ) update k increase j by 1 and add into k then print k ( i.e 10 ) update k increase j by 1 and add into k then print k ( i.e 15 ) update k increase j by 1 and add into k then print k ( i.e 21 ) update k . . and so on.
Approach used is very simple. Iterate for loop till the value given n and for each iteration increase j by 1 and add it into k, which will simply print the triangular number series till n.
Below is the program implementing above approach:
Output :
1 3 6 10 15
Time complexity : O(n)
Auxiliary Space : O(1), since no extra space has been taken.
Alternate Solution :
The solution is based on the fact that i-th Triangular number is sum of first i natural numbers, i.e., i * (i + 1)/2
Output :
1 3 6 10 15
Time complexity : O(n)
Auxiliary Space : O(1) , since no extra space has been taken.