Discussion on Java at the COJ. This is the place to clear your doubts about these languages, and to share with the community the new things you learn about them.
WIL
Posts: 11
Joined: 8 years ago
Gender:

An algorithm for solving exercises such as the Fibonacci series???

I'm interesting in learn!!!

jelara
Posts: 37
Joined: 8 years ago
Gender:

Re: About efficient algorithms in java??

Well, Fibonacci can be solved in many ways (with recursion, iteration, precalculation, etc). One of the fastests I know (if not the fastest), is to use the closed solution of the recurrence. That can be implemented in many languages.

luismawolf
Posts: 30
Joined: 5 years ago
Gender:

Re: About efficient algorithms in java??

package fibonacci;

import java.util.Scanner;

public class Fibonacci {

static int fibonacci(int numero) {
if ((numero == 0) || (numero == 1)) {
return 1;
} else {
return fibonacci(numero - 1) + fibonacci(numero - 2);
}
}

public static void main(String[] args) {
Scanner miScanner = new Scanner(System.in);
System.out.println("Entre un número: ");
int prueba = miScanner.nextInt();
System.out.println(fibonacci(prueba));
}

}

isaac
Posts: 83
Joined: 4 years ago
Gender:

Re: About efficient algorithms in java??

La sucesion de Fibonnaci, si se necesitan varios términos de ella, es mejor calcularla de la forma F[n] = F[n-1] + F[n-2], pero cuando se necesita un término en particular, se puede calcular en O(log2 N) utilizando propiedades de las matrices. La matriz:

0 1
1 1