Added a function to get the factorial of a number

This commit is contained in:
2020-01-31 19:32:30 -05:00
parent 93bad2b80d
commit 0bbb3ba406
2 changed files with 135 additions and 0 deletions

View File

@@ -625,6 +625,38 @@ public class Algorithms{
fibNums.remove(fibNums.size() - 1);
return fibNums;
}
//This function returns the factorial of the number passed to it
public static Integer factorial(Integer num){
Integer fact = 1; //The value of the factorial
//TODO: Throw an exception for values < 0
//Loop through every number up to and including num and add the product to the factorial
for(Integer cnt = 2;cnt.compareTo(num) <= 0;++cnt){
fact *= cnt;
}
return fact;
}
public static Long factorial(Long num){
Long fact = 1L; //The value of the factorial
//Loop through every number up to and including num and add the product to the factorial
for(Long cnt = 2L;cnt.compareTo(num) <= 0;++cnt){
fact *= cnt;
}
return fact;
}
public static BigInteger factorial(BigInteger num){
BigInteger fact = BigInteger.valueOf(1L);
//Loop through every number up to and including num and add the product to the factorial
for(BigInteger cnt = BigInteger.TWO;cnt.compareTo(num) <= 0;cnt = cnt.add(BigInteger.ONE)){
fact = fact.multiply(cnt);
}
return fact;
}
//This function returns the sum of all elements in the list
public static Integer getSum(ArrayList<Integer> nums){
//If a blank list was passed to the function return 0 as the sum