Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Greatest Common Divisor Loop [duplicate]

Tags:

java

I'm doing some self-taught Java, but can't seem to figure out the issue in this loop:

The question was to find the greatest common divisor of two integers n1 and n2 where d is the lesser value. The method is to decrement d until a GCD or it reaches 1...here's where I'm at so far:

    Scanner input = new Scanner(System.in);
    System.out.println("Please enter two integers: ");
    int n1 = input.nextInt();
    int n2 = input.nextInt();

    int d = 0;
    int temp = 0;
    //finds the lowest value
    if(n1 < n2) {
        temp = n1;
        n1 = n2;
        n2 = temp;
    }

    for(d = n1;(n1 % d !=0 && n2 % d != 0);d--)  {

    }

    System.out.println("The GCD of " + n1 + " and " + n2 + " is " + d);

Any pointers?

like image 621
mikedugan Avatar asked Sep 12 '26 02:09

mikedugan


2 Answers

The logic in here is wrong:

(n1 % d !=0 && n2 % d != 0)

change to:

(n1 % d !=0 || n2 % d != 0)

Or the code will stop once is saw a divisor of n1 or n2, instead of their GCD, since the loop termination condition should be the negation of what you want to do.

like image 80
zw324 Avatar answered Sep 13 '26 16:09

zw324


Iterative

public static long gcd(long a, long b){
   long factor= Math.max(a, b);
   for(long loop= factor;loop > 1;loop--){
      if(a % loop == 0 && b % loop == 0){
         return loop;
      }
   }
   return 1;
}

Iterative Euclid's Algorithm

public static int gcd(int a, int b) //valid for positive integers.
{
    while(b > 0)
    {
        int c = a % b;
        a = b;
        b = c;
    }
    return a;
}

Optimized Iterative

static int gcd(int a,int b)
    {
        int min=a>b?b:a,max=a+b-min, div=min;
        for(int i=1;i<min;div=min/++i)
            if(max%div==0)
                return div;
        return 1;
    }

Recursive

public static long gcd(long a, long b){
   if(a == 0) return b;
   if(b == 0) return a;
   if(a > b) return gcd(b, a % b);
   return gcd(a, b % a);
}

Built-in

import java.math.BigInteger;

public static long gcd(long a, long b){
   return BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)).longValue();
}

via - http://rosettacode.org/wiki/Greatest_common_divisor

like image 41
Bishal Ghimire Avatar answered Sep 13 '26 15:09

Bishal Ghimire



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!