Skip to content

Instantly share code, notes, and snippets.

@alashow
Last active October 2, 2017 06:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alashow/824dfad447a2deabc752952454d4be63 to your computer and use it in GitHub Desktop.
Save alashow/824dfad447a2deabc752952454d4be63 to your computer and use it in GitHub Desktop.
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