fibonacci zahlen programmieren code example

Example 1: fibunacci java

// WARNING: The function assumes that 'fib(0)=0' and 'fib(1)=1'
// Returns the number of the fibonacci sequence at index 'n'
public static int fib(int n) {
	if (n < 2) // No difference if '<' or '<=', because 'fib(2)=2'.
		return n;
	return fib(n-1) + fib(n-2); // Uses the recursion method for solving
}

Example 2: fibonacci java

import info1.*;

public class FibonacciDemo1{

  public static void main(String[] args){

    System.out.print("Geben Sie ein Zahl an: ");

    int a = Console.in.readInt();

    System.out.println("fib("+a+") = " + fibonacci(a));

  }

  private static int fibonacci(int a){

    if (a==1||a==2) return 1;

    else return fibonacci(a-1)+fibonacci(a-2);

  }

}

Tags:

Java Example