mirror of
https://bitbucket.org/Mattrixwv/javaclasses.git
synced 2025-12-07 07:23:57 -05:00
Added a function to get the factorial of a number
This commit is contained in:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user