Created
September 19, 2014 17:58
-
-
Save jamiecurran/8b31e7f58f7f2059b3f9 to your computer and use it in GitHub Desktop.
Factorials - 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.stream.IntStream; | |
public class Factorials { | |
public static void main(String[] args) { | |
Integer input = Integer.valueOf(args[0]); | |
System.out.printf("factorial of %d (v7) = %d\n", input, version7(input)); | |
System.out.printf("factorial of %d (v8) = %d\n", input, version8(input)); | |
System.out.printf("factorial of %d (recursive) = %d\n", input, recursive(input)); | |
System.out.printf("factorial of %d (tailRecursive) = %d\n", input, tailRecursive(input)); | |
} | |
private static Integer version7(Integer input){ | |
Integer sum = 1; | |
for(int i = 1; i <= input; i++) { | |
sum = sum * i; | |
} | |
return sum; | |
} | |
private static Integer version8(Integer input){ | |
return IntStream.rangeClosed(1, input).reduce((x, y) -> x * y).getAsInt(); | |
} | |
private static Integer recursive(Integer input){ | |
if(input == 0) | |
return 1; | |
else | |
return input * recursive(input - 1); | |
} | |
private static Integer tailRecursive(Integer input){ | |
return withCount(1, input); | |
} | |
private static Integer withCount(Integer count, Integer input){ | |
if(input == 0) | |
return count; | |
else | |
return withCount((count * input), input - 1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment