Java program – Euclid’s algorithm

by Nideesh C on April 29, 2011 · 0 comments

in Java Programming




public class Euclid {

    // recursive implementation
    public static int gcd(int p, int q) {
        if (q == 0) return p;
        else return gcd(q, p % q);
    }

    // non-recursive implementation
    public static int gcd2(int p, int q) {
        while (q != 0) {
            int temp = q;
            q = p % q;
            p = temp;
        }
        return p;
    }

    public static void main(String[] args) {
        int p = Integer.parseInt(args[0]);
        int q = Integer.parseInt(args[1]);
        int d  = gcd(p, q);
        int d2 = gcd2(p, q);
        System.out.println("gcd(" + p + ", " + q + ") = " + d);
        System.out.println("gcd(" + p + ", " + q + ") = " + d2);
    }
}


/*************************************************************************
 *  Execution:    java Euclid p q
 *
 *  Reads two command-line arguments p and q and computes the greatest
 *  common divisor of p and q using Euclid's algorithm.
 *
 *  Remarks
 *  -----------
 *    - may return the negative of the gcd if p is negative
 *
 *************************************************************************/



Not Satisfied ? Just search & get the result

Related Posts Plugin for WordPress, Blogger...
Be Sociable, Share!

Related posts:

  1. C program to find the GCD and LCM of two integers output the results along with the given integers. Use Euclids’ algorithm
  2. Java program – Newton’s method with functions
  3. Java program – Converting to binary
  4. Java program – Generating a random sequence
  5. Java program – Integer multiplication and division

Leave a Comment

Previous post:

Next post: