Added exceptions to the factorial functions

This commit is contained in:
2020-06-07 23:26:42 -04:00
parent 0491488a64
commit 9829b8dc29

View File

@@ -26,6 +26,7 @@ package mattrixwv;
import java.math.BigInteger; import java.math.BigInteger;
import java.security.InvalidParameterException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
@@ -626,10 +627,13 @@ public class Algorithms{
return fibNums; return fibNums;
} }
//This function returns the factorial of the number passed to it //This function returns the factorial of the number passed to it
public static Integer factorial(Integer num){ public static Integer factorial(Integer num) throws InvalidParameterException{
Integer fact = 1; //The value of the factorial Integer fact = 1; //The value of the factorial
//TODO: Throw an exception for values < 0 //If the number passed in is < 0 throw an exception
if(num < 0){
throw new InvalidParameterException("n! cannot be negative");
}
//Loop through every number up to and including num and add the product to the factorial //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){ for(Integer cnt = 2;cnt.compareTo(num) <= 0;++cnt){
fact *= cnt; fact *= cnt;
@@ -637,9 +641,13 @@ public class Algorithms{
return fact; return fact;
} }
public static Long factorial(Long num){ public static Long factorial(Long num) throws InvalidParameterException{
Long fact = 1L; //The value of the factorial Long fact = 1L; //The value of the factorial
//If the number passed in is < 0 throw an exception
if(num < 0){
throw new InvalidParameterException("n! cannot be negative");
}
//Loop through every number up to and including num and add the product to 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){ for(Long cnt = 2L;cnt.compareTo(num) <= 0;++cnt){
fact *= cnt; fact *= cnt;
@@ -647,9 +655,13 @@ public class Algorithms{
return fact; return fact;
} }
public static BigInteger factorial(BigInteger num){ public static BigInteger factorial(BigInteger num) throws InvalidParameterException{
BigInteger fact = BigInteger.valueOf(1L); BigInteger fact = BigInteger.valueOf(1L);
//If the number passed in is < 0 throw an exception
if(num.compareTo(BigInteger.ZERO) < 0){
throw new InvalidParameterException("n! cannot be negative");
}
//Loop through every number up to and including num and add the product to the factorial //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)){ for(BigInteger cnt = BigInteger.TWO;cnt.compareTo(num) <= 0;cnt = cnt.add(BigInteger.ONE)){
fact = fact.multiply(cnt); fact = fact.multiply(cnt);