diff --git a/src/main/java/mattrixwv/Algorithms.java b/src/main/java/mattrixwv/Algorithms.java index a421086..90c854d 100644 --- a/src/main/java/mattrixwv/Algorithms.java +++ b/src/main/java/mattrixwv/Algorithms.java @@ -26,6 +26,7 @@ package mattrixwv; import java.math.BigInteger; +import java.security.InvalidParameterException; import java.util.ArrayList; import java.util.Collections; @@ -626,10 +627,13 @@ public class Algorithms{ return fibNums; } //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 - //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 for(Integer cnt = 2;cnt.compareTo(num) <= 0;++cnt){ fact *= cnt; @@ -637,9 +641,13 @@ public class Algorithms{ return fact; } - public static Long factorial(Long num){ + public static Long factorial(Long num) throws InvalidParameterException{ 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 for(Long cnt = 2L;cnt.compareTo(num) <= 0;++cnt){ fact *= cnt; @@ -647,9 +655,13 @@ public class Algorithms{ return fact; } - public static BigInteger factorial(BigInteger num){ + public static BigInteger factorial(BigInteger num) throws InvalidParameterException{ 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 for(BigInteger cnt = BigInteger.TWO;cnt.compareTo(num) <= 0;cnt = cnt.add(BigInteger.ONE)){ fact = fact.multiply(cnt);