Example of Fibonacci algorithm implemented in Java
- 2020-04-01 04:08:26
- OfStack
This article illustrates how to implement the Fibonacci algorithm in Java. Share with you for your reference. The details are as follows:
package com.yenange.test2;
import java.util.Scanner;
public class Fibonacci {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("----------- The first 1 algorithm ------------");
int num1 = 1;
int num2 = 1;
int temp, count;
System.out.println(" Please enter the number you want to query (>=2):");
count = input.nextInt();
System.out.println(" The first 1 The number is :1");
System.out.println(" The first 2 The number is :1");
for (int i = 3; i <= count; i++) {
temp = num2;
num2 += num1;
System.out.println(" The first " + i + " The number is :" + num2);
num1 = temp;
}
System.out.println("----------- The first 2 algorithm ------------");
System.out.println(" The first " + count + " The number is :" + cal(count));
System.out.println("----------- The first 3 algorithm ------------");
int[] arr = new int[count];
arr[0] = 1;
arr[1] = 1;
for (int i = 2; i < arr.length; i++) {
arr[i] = arr[i - 1] + arr[i - 2];
System.out.println(" The first " + (i + 1) + " The number is :" + arr[i]);
}
}
static int cal(int count) {
if (count <= 2) {
return 1;
}
return cal(count - 1) + cal(count - 2);
}
}
I hope this article has been helpful to your Java programming.