mirror of
https://bitbucket.org/Mattrixwv/javaclasses.git
synced 2025-12-06 15:03:58 -05:00
Added exceptions to the factorial functions
This commit is contained in:
@@ -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);
|
||||
|
||||
Reference in New Issue
Block a user