mirror of
https://bitbucket.org/Mattrixwv/javaclasses.git
synced 2025-12-06 15:03:58 -05:00
Added functions to find the gcd of 2 numbers
This commit is contained in:
@@ -34,6 +34,9 @@ import mattrixwv.exceptions.InvalidResult;
|
||||
|
||||
|
||||
public class Algorithms{
|
||||
public static <T> T getNum(T num1){
|
||||
return num1;
|
||||
}
|
||||
//This function returns a list with all the prime numbers <= goalNumber
|
||||
public static ArrayList<Integer> getPrimes(Integer goalNumber){
|
||||
ArrayList<Integer> primes = new ArrayList<Integer>(); //Holds the prime numbers
|
||||
@@ -722,6 +725,34 @@ public class Algorithms{
|
||||
|
||||
return fact;
|
||||
}
|
||||
//This function returns the GCD of the two numbers sent to it
|
||||
public static int gcd(int num1, int num2){
|
||||
int gcd = 1;
|
||||
for(int cnt = 1;(cnt <= num1) && (cnt <= num2);++cnt){
|
||||
if(((num1 % cnt) == 0) && ((num2 % cnt) == 0)){
|
||||
gcd = cnt;
|
||||
}
|
||||
}
|
||||
return gcd;
|
||||
}
|
||||
public static long gcd(long num1, long num2){
|
||||
long gcd = 1;
|
||||
for(long cnt = 1;(cnt <= num1) && (cnt <= num2);++cnt){
|
||||
if(((num1 % cnt) == 0) && ((num2 % cnt) == 0)){
|
||||
gcd = cnt;
|
||||
}
|
||||
}
|
||||
return gcd;
|
||||
}
|
||||
public static BigInteger gcd(BigInteger num1, BigInteger num2){
|
||||
BigInteger gcd = BigInteger.ONE;
|
||||
for(BigInteger cnt = BigInteger.ONE;(cnt.compareTo(num1) <= 0) && (cnt.compareTo(num2) <= 0);cnt.add(BigInteger.ONE)){
|
||||
if(num1.mod(cnt).equals(BigInteger.ZERO) && num2.mod(cnt).equals(BigInteger.ZERO)){
|
||||
gcd = cnt;
|
||||
}
|
||||
}
|
||||
return gcd;
|
||||
}
|
||||
//This function returns the sum of all elements in the list
|
||||
public static int 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