Last active
March 21, 2020 16:11
-
-
Save mekilis/0a5c86206519da226978587135b52e4a to your computer and use it in GitHub Desktop.
The factorial function using the iterative technique
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
private static long factorialForLoop(long n) { | |
long result = 1; | |
for (int i = 1; i <= n; i++) { | |
result *= i; | |
} | |
return result; | |
} | |
private static long factorialWhileLoop(long n) { | |
if (n <= 1) | |
return 1; | |
long result = n; | |
while (n-- > 1) { | |
result *= n; | |
} | |
return result; | |
} | |
private static long factorialReduceOptional(long n) { | |
if (n <= 1) | |
return 1; | |
List<Integer> factorsList = IntStream.range(1, (int) n+1) | |
.boxed() | |
.collect(Collectors.toList()); | |
return factorsList.stream() | |
.reduce((a, b) -> a * b) | |
.orElseThrow(() -> new RuntimeException("Failed to perform reduce operation")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment