Saturday, December 7, 2013

Java Program to find nth term in a TRIBONACCI series

 // 0,1,1,2,4,7,13,.....


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Tribonacci {

    /**
     * @param args
     */
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                System.in));
        System.out.println(" Enter the number ");
        int num = Integer.parseInt(reader.readLine());
        int first = 0, second = 1, third = 1, nthTerm = 0;
        int num1 = num;
        if (num == 1)
            nthTerm = 0;

        if (num == 2 || num == 3)
            nthTerm = 1;

        while (num > 3) {
            nthTerm = first + second + third;
            // System.out.print(d +"\t");
            num--;
            first = second;
            second = third;
            third = nthTerm;
        }
        System.out.print(num1 + "th term of the Tribonacci is " + nthTerm);
    }
}

No comments:

Post a Comment