Factorial by definition is for positive integers.
I do not understand what the program requires.
Error message: Be sure that the program works correctly if the entered number is less than 0.
So, I have already tried
1. converting the negative number into positive and calculating the factorial. Printing it as it is.
2. Printing the above result with - prefix.
What am I missing?
package com.codegym.task.task15.task1531;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
/*
Factorial
*/
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int input = Integer.parseInt(reader.readLine());
reader.close();
System.out.println(factorial(input));
}
public static String factorial(int n) {
boolean isNegative = false;
String res = "";
if(n < 0) {
n = n*-1;
isNegative = true;
}
BigDecimal num=new BigDecimal(n);
if(isNegative) {
res = "-" + fact(num).toString();
}else
res = fact(num).toString();
return res;
}
public static BigDecimal fact(BigDecimal num) {
if (num.compareTo((new BigDecimal("1"))) == -1) {
return new BigDecimal("1");
} else {
return (num.multiply(fact(num.subtract(new BigDecimal("1")))));
}
}
}