Created
January 24, 2014 13:15
-
-
Save edolopez/8597008 to your computer and use it in GitHub Desktop.
Fibonacci with method in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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