From 868b78e27028824add34560816dc38c4888da6fe Mon Sep 17 00:00:00 2001 From: Bogdan Popov Date: Sun, 16 Oct 2016 22:37:30 +0300 Subject: [PATCH 1/3] Fibonacci function added --- src/TechInterview/Fibonacci.java | 73 ++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 src/TechInterview/Fibonacci.java diff --git a/src/TechInterview/Fibonacci.java b/src/TechInterview/Fibonacci.java new file mode 100644 index 0000000..3cb3925 --- /dev/null +++ b/src/TechInterview/Fibonacci.java @@ -0,0 +1,73 @@ +package forhacktoberfest; + +import java.util.function.LongSupplier; +import java.util.stream.LongStream; + +/** + * Cracking the Code Interview + * My solutions of how to generate the nth Fibonacci number. + * Here are three different solutions to find this number + */ + +public class Fibonacci { + + public static void main(String[] args) { + + System.out.println(fibStream(35)); + System.out.println(fib(35)); + System.out.println(iterFib(35)); + + } + + // basic algorithm without cache + + public static int fib(int n) { + + if (n == 0) return 0; + if (n == 1) return 1; + return fib(n - 1) + fib(n - 2); + + } + + // iterative algorithm without cache + + public static int iterFib(int n) { + + return iter(1, 0, n); + + } + + private static int iter(int a, int b, int count) { + + if (count == 0) return b; + return iter(a + b, a, count - 1); + + } + + // solution with stream api + + public static long fibStream(int n) { + + return LongStream.generate(new FibonacciSupplier()) + .skip(n - 1) + .findFirst().getAsLong(); + + } + + private static class FibonacciSupplier implements LongSupplier { + + private long prev = 0L; + private long next = 1L; + + @Override + public long getAsLong() { + long current = next; + next = prev + current; + prev = current; + return current; + } + + } + + +} From 70bdd568e7eb32138af8c27d42ef0bf60e598f7b Mon Sep 17 00:00:00 2001 From: Bogdan Date: Sun, 16 Oct 2016 22:43:01 +0300 Subject: [PATCH 2/3] some spaces removed --- src/TechInterview/Fibonacci.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/TechInterview/Fibonacci.java b/src/TechInterview/Fibonacci.java index 3cb3925..9a49c67 100644 --- a/src/TechInterview/Fibonacci.java +++ b/src/TechInterview/Fibonacci.java @@ -68,6 +68,4 @@ public long getAsLong() { } } - - } From fb4d3f79e1c0f563fd9478a4380fa5bea82dd56e Mon Sep 17 00:00:00 2001 From: Bogdan Date: Thu, 20 Oct 2016 14:10:46 +0300 Subject: [PATCH 3/3] package changed --- src/TechInterview/Fibonacci.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/TechInterview/Fibonacci.java b/src/TechInterview/Fibonacci.java index 9a49c67..46d0463 100644 --- a/src/TechInterview/Fibonacci.java +++ b/src/TechInterview/Fibonacci.java @@ -1,4 +1,4 @@ -package forhacktoberfest; +package TechInterview; import java.util.function.LongSupplier; import java.util.stream.LongStream;