Skip to content

Instantly share code, notes, and snippets.

@edolopez
Created January 24, 2014 13:15
Show Gist options
  • Save edolopez/8597008 to your computer and use it in GitHub Desktop.
Save edolopez/8597008 to your computer and use it in GitHub Desktop.
Fibonacci with method in Java
import java.util.Scanner;
public class Fibonacci {
public static void main (String [] args) {
Scanner input = new Scanner(System.in);
// Asks for the first number
int num = input.nextInt();
long fibo = findsFibo(num); // Executes the method to find Fibonacci
System.out.println(fibo);
// Asks for the second number
num = input.nextInt();
fibo = findsFibo(num); // Executes the method to find Fibonacci
System.out.println(fibo);
}
// This section only finds the Fibonacci of
// an integer number, and returns a long value
// which is the result.
public static long findsFibo(int n) {
long fn_2 = 1; // Fib -1
long fn_1 = 0; // Fib 0
long fn = 0; // Adding the last 2
for (int i = 1; i <= n; i++) {
fn = fn_2 + fn_1;
fn_2 = fn_1;
fn_1 = fn;
}
return fn;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment