Skip to content

Instantly share code, notes, and snippets.

@alashow

alashow/Fibonacci.java

Last active Oct 2, 2017
Embed
What would you like to do?
Fibonacci in Java using tail call.
package tm.alashow.homework.datastructures.second;
import java.util.Locale;
import java.util.Scanner;
/**
* Created by alashov on 10/1/17.
*/
public class Fibonacci {
/**
* Long's can't hold more than {@link Long#MAX_VALUE}
* and Fn=93's value is bigger than that.
*/
private final int LIMIT = 92;
public static void main(String[] args) {
new Fibonacci().init();
}
private void init() {
// forever and ever
while ((1 + 1) == 2) {
Scanner scanner = new Scanner(System.in);
print("Enter Fn: ");
try {
int n = scanner.nextInt();
// checks the limit and resets n to limit if exceeds
if (n > LIMIT) {
println("\nCan't do dat much.. max I can do is %d", LIMIT);
n = LIMIT;
}
println("\nFibonacci '%d': ", n);
// seed is 0 and 1
fibonacci(0, 1, n);
} catch (Exception e) {
println("Something fishy happened with the input, try again.");
}
//double space
println("\n");
}
}
/**
* Calculates and prints each step of Fibonacci using tail call.
*
* @param a n-1
* @param b n-2
* @param n sequence
*
* @return last result
*/
private long fibonacci(long a, long b, long n) {
print("%d, ", a);
return n == 0 ? a : fibonacci(b, a + b, n - 1);
}
// print utils
private static void print(Object object) {
System.out.print(object);
}
private static void println(Object object) {
System.out.println(object);
}
private static void print(String string, Object... format) {
print(String.format(Locale.ROOT, string, format));
}
private static void println(String string, Object... format) {
println(String.format(Locale.ROOT, string, format));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment