# Calculate a triangle number

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

A triangular number is the number of dots in an equilateral triangle evenly filled with dots. For example, three dots can be arranged in a triangle; thus three is a triangle number. The nth triangle number is the number of dots in a triangle with n dots on a side.

## Implementations

### C

```#include <stdio.h>

unsigned triangularNumber(unsigned n);

const char *suffix[] = {" ","st","nd","rd"};

int main(int argc, char *argv[]) {
int n = 0,m;
unsigned t;

if ((argc < 2) ||
(sscanf(argv,"%d",&n) != 1) ||
(n <= 0)) {
printf("\nusage %s <n>\n",argv);
printf(" where <n> is a positive integer\n");
return -1;
}
t = (int)(n * (((float)n + 1.0) / 2.0));
if (t == triangularNumber(n)) {
m = n % 10;
printf("\nThe %d%s triangular number is %d\n",
n,
((m > 0) && (m < 4)) ? suffix[m] : "th",
t);
} else {
printf("\nerror\n");
}
return 0;
}

unsigned triangularNumber(unsigned n) {
if (n == 1) return 1;
return n + triangularNumber(n-1);
}
```

### Common Lisp

``` (loop for i from 0 below 1000 collecting (* i (1+ i) 1/2))
```

### Erlang

```triangle_numbers(N) ->
triangle_numbers(N, 1, []).

triangle_numbers(N, I, Result) when N < I ->
lists:reverse(Result);
triangle_numbers(N, I, Result) ->
Tn = I * (I+1) div 2,
triangle_numbers(N, I+1, [Tn | Result]).
```

### Haskell

```tri :: Fractional a => a -> a
tri n = n * (n + 1) / 2
```

### Java

This code will print the first 1000 triangle numbers to the system console.

```	public static void main(String[] args) {

for (int i = 1 ; i < 1000 ; i++) {

int n = i*(i+1)/2;
System.out.println( "n="+i+" triangle number="+n );

}

}
```

### OCaml

```# let triangle_numbers n = Array.init n (fun i -> i*(i+1)/2);;
val triangle_numbers : int -> int array
```

For example:

```# triangle_numbers 10;;
- : int array = [|0; 1; 3; 6; 10; 15; 21; 28; 36; 45|]
```

### Perl

```print for map {"n=\$_ triangle number=".\$_*(\$_+1)/2, "\n"} 1..1000;
```

### PHP

```<?php
foreach ( range(1, 1000) as \$i ) {
\$triangle_numbers[] = \$i * ( \$i + 1 ) / 2;
}
?>
```

### Python

```def triangle_numbers(n):
return [i*(i+1)/2 for i in xrange(n)]
```

For example:

```>>> triangle_numbers(10)
[0, 1, 3, 6, 10, 15, 21, 28, 36, 45]
```

### Ruby

``` def triangle_numbers(n)
Array.new(n) {|i| i*(i+1)/2 }
end
```

### Seed7

This code will print the first 1000 triangle numbers to the system console.

```\$ include "seed7_05.s7i";

const proc: main is func
local
var integer: num is 0;
begin
for num range 1 to 1000 do
writeln("n=" <& num <&
" triangle number=" <& num * succ(num) div 2);
end for;
end func;
```

### Tcl

```for {set i 1} {\$i <= 1000} {incr i} {pust [expr {\$i*(\$i+1)/2}]}
```

### Zsh

```for i in {0..9}; print \$((i * (i+1) / 2))
```