Calculate a triangle number
From CodeCodex
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.
Contents |
[edit] Implementations
[edit] 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 );
}
}
[edit] 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|]
[edit] Perl
print for map {"n=$_ triangle number=".$_*($_+1)/2, "\n"} 1..1000;
[edit] PHP
<?php foreach ( range(1, 1000) as $i ) { $triangle_numbers[] = $i * ( $i + 1 ) / 2; } ?>
[edit] 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]
[edit] 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;
[edit] Ruby
def triangle_numbers(n)
Array.new(n) {|i| i*(i+1)/2 }
end
[edit] Common Lisp
(loop for i from 0 below 1000 collecting (* i (1+ i) 1/2))
[edit] Zsh
for i in {0..9}; print $((i * (i+1) / 2))
[edit] 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[1],"%d",&n) != 1) ||
(n <= 0)) {
printf("\nusage %s <n>\n",argv[0]);
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);
}
Categories: Math | Recursion | Java | Ruby | Objective Caml | Perl | Python | Seed7 | Common Lisp | Zsh | C

