In: Computer Science
In Java please What happens if you call factorial( with a negative value of n? With a large value of say 35? Write a recursive function that takes an integer n as its argument and returns ln(n!)
Below is the Java Solution with output screenshot
Code :
import java.util.Scanner;
public class Solution {
// main method
public static void main(String[] args) {
int n;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
n = sc.nextInt();
System.out.println("Factorial of " + n + " = " + factorial(n));
}
// recursive factorial function
public static int factorial(int n){
if(n<=0){
return 1;
}
return n*factorial(n-1);
}
}
Output :
Case 1: if we call factorial() function with negative value
Answer : The factorial is the product of all positive integers less than or equal to n. Hence we can't calculate factorial of negative numbers. and if we do pass a negative value we will get an error.
Case 2 : pass large number like 35 in factorial function
Factorial of a large number like 35 is a very big number (~1040) which can't be stored in integer value because integers can only store values up to 109 range
Hence if we call factorial function with large value i.e factorial(35) then we will get 0 output because of integer overflow.