quarta-feira, 25 de janeiro de 2017

Java - fibonnaci number

In mathematics, the Fibonacci numbers are the numbers in the following integer sequence, called the Fibonacci sequence, and characterized by the fact that every number after the first two is the sum of the two preceding ones.
Source: Wikipedia.

Fibonacci numbers can be represented in the following formula:
F(n) = F(n-1) + F(n-2)

F(1) = 1
F(2) = 1
F(3) = F(2) + F(1) -> 1 + 1 = 2
F(4) = F(3) + F(2) -> 2 + 3 = 5

The algorithm that I will show here is not recursive:

  
public static int fibonnaci(int number) {

    if (number <= 2) {
        return 1;
    }

    int previous = 1;
    int result = 1;

    for (int i = 3; i <= number; i++) {
        int temp = result;
        result = previous + result;
        previous = temp;
    }

    return result;

}

Nenhum comentário:

Postar um comentário