Updated gcd algorithm

This commit is contained in:
2021-02-07 11:37:38 -05:00
parent eb483ea795
commit aa9d136062

View File

@@ -727,31 +727,37 @@ public class Algorithms{
}
//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;
while((num1 != 0) && (num2 != 0)){
if(num1 > num2){
num1 %= num2;
}
else{
num2 %= num1;
}
}
return gcd;
return num1 | num2;
}
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;
while((num1 != 0) && (num2 != 0)){
if(num1 > num2){
num1 %= num2;
}
else{
num2 %= num1;
}
}
return gcd;
return num1 | num2;
}
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;
while(!num1.equals(BigInteger.ZERO) && !num2.equals(0)){
if(num1.compareTo(num2) > 0){
num1 = num1.mod(num2);
}
else{
num2 = num2.mod(num1);
}
}
return gcd;
return num1.or(num2);
}
//This function returns the sum of all elements in the list
public static int getSum(ArrayList<Integer> nums){