Posts

Showing posts from March, 2020

Factorial by Different Styles in Java

Here is a collection of methods of calculating factorial by different programming styles. class Factorial { // Iteration static long iterativeFactorial( int n) { long r = 1; for ( int i=1; i<=n; i++) r*=i; return r; } // Recursion static long recursiveFactorial( int n) { return n == 0 ? 1 : n * recursiveFactorial(n-1); } // Tail-recursion static long tailRecurFactorial( int n) { return tailRecurHelper(1L, n); } static long tailRecurHelper( long acc, int n) { return n == 0 ? acc : tailRecurHelper(acc*n, n-1); } // Lambda and Recursion static Function<Integer, Long> lambdaRecurFactorial = x -> x==0 ? 1L : x * Factorial.lambdaRecurFactorial.apply(x-1); // Stream static long streamFactorial ( int n) { return LongStream.rangeClosed(1, n) .reduce(1, (a, b) -> a*b); } /...

Fibonacci Sequence by Modern Java

Fibonacci sequence is one of the well known wonders in mathematics and sciences.  The sequence that captures a type of essence of the universe has always been intriguing.  Below is the code for generating the sequence that the algorithm can be written in an elegant way by modern Java. class Tuple <T, U> { public final T _1; public final U _2; public Tuple(T t, U u) { this ._1 = t; this ._2 = u; } } class Fibonnaci { public static void main(String[] args) { Function<Integer, Stream<Integer>> getFiboStream = (n) -> { Tuple<Integer, Integer> seed = new Tuple<>(1, 1); UnaryOperator<Tuple<Integer, Integer>> f = (x) -> new Tuple<>(x._2, x._1 + x._2); return Stream.iterate(seed, f) .map(x -> x._1) .limit(n); }; String result = getFiboStream.apply(20) ...