The Fibonacci sequence is the infinite sequence of natural numbers, which begins with twice the number 1 or, often in modern notation, is additionally provided with a leading number 0. In the further sequence of numbers, the sum of two consecutive numbers results in the number immediately following it.
import java.util.Scanner;
public class Fibonacci {
private static void fibonacciAlgorithm(int quantitiy) {
if (quantitiy == 1) {
System.out.print("0");
return;
}
int first = 0;
int second = 1;
int third;
System.out.print(first + " " + second);
for (int i = 3; i <= quantitiy; i++) {
third = first + second;
System.out.print(" " + third);
first = second;
second = third;
}
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter the number of Fibonacci numbers to be generated: ");
int quantitiy = reader.nextInt();
reader.close();
fibonacciAlgorithm(quantitiy);
}
}
Enter the number of Fibonacci numbers to be generated: 10
0 1 1 2 3 5 8 13 21 34
import java.util.Scanner;
public class Fibonacci {
private static int fibonacciAlgorithm(int number) {
if (number == 0) {
return 0;
}
if (number == 1) {
return 1;
}
return fibonacciAlgorithm(number - 1) + fibonacciAlgorithm(number -2);
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter n-th number of Fibonacci Sequence: ");
int number = reader.nextInt();
reader.close();
System.out.println(fibonacciAlgorithm(number));
}
}
Enter n-th number of Fibonacci Sequence: 9
34