Math: Triangular Numbers

03 November 2011
A triangulat number is define as 1 + 2 + 3 + ... + n for n = 1, 2, ..., and so on. So, the first few numbers are 1, 3, 6, 10, ... Write the following method that return a triangular number:


public static int getTriangularNumber(int n)


Write test program that displays the first 100 triangular number with 10 numbers on each line.

Input:
100

Ouput:
1 3 6 10 15 21 28 36 45 55
66 78 91 105 120 136 153 171 190 210
231 253 276 300 325 351 378 406 435 465
496 528 561 595 630 666 703 741 780 820
861 903 946 990 1035 1081 1128 1176 1225 1275
1326 1378 1431 1485 1540 1596 1653 1711 1770 1830
1891 1953 2016 2080 2145 2211 2278 2346 2415 2485
2556 2628 2701 2775 2850 2926 3003 3081 3160 3240
3321 3403 3486 3570 3655 3741 3828 3916 4005 4095
4186 4278 4371 4465 4560 4656 4753 4851 4950 5050

Main.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package triangularnumbers;

import java.util.Scanner;

/**
 *
 * @author dekwan
 */
public class Main
{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        // TODO code application logic here
        Scanner scan = new Scanner(System.in);

        int number = scan.nextInt();

        sop("\n");

        for (int i = 0; i < number; i += 10)
        {
            for (int j = 1; j <= 10; j++)
            {
                sop(getTriangularNumber(i + j) + " ");
            }
            sop("\n");
        }
    }

    public static int getTriangularNumber(int n)
    {
        return (n * (n + 1)) / 2;
    }

    public static void sop(String str)
    {
        System.out.print(str);
    }
}




0 comments:

Catat Ulasan

Terima kasih kerana memberi ulasan...