Skip to content

Instantly share code, notes, and snippets.

@aerphanas
Created December 26, 2022 08:32
Show Gist options
  • Select an option

  • Save aerphanas/bc3c4070912ffbd3145d7217c5a9f2de to your computer and use it in GitHub Desktop.

Select an option

Save aerphanas/bc3c4070912ffbd3145d7217c5a9f2de to your computer and use it in GitHub Desktop.
factorial
import java.util.Scanner;
import java.util.function.Function;
public class Factorialf
{
// Declare the factorialFn variable outside the factorial method
static Function<Integer, Integer> factorialFn = new Function<Integer, Integer>() {
@Override
public Integer apply(Integer x) {
if (x == 0) {
return 1;
}
return x * factorialFn.apply(x - 1);
}
};
public static int factorial(int n) {
return factorialFn.apply(n);
}
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
int number = scanner.nextInt();
int fact = 1;
// Call the factorial function
fact = factorial(number);
// Print the result
System.out.println("The factorial of " + number + " is " + fact);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment