Skip to content

Instantly share code, notes, and snippets.

@mekilis
Last active March 21, 2020 16:11
Show Gist options
  • Save mekilis/0a5c86206519da226978587135b52e4a to your computer and use it in GitHub Desktop.
Save mekilis/0a5c86206519da226978587135b52e4a to your computer and use it in GitHub Desktop.
The factorial function using the iterative technique
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