Search:

# Greatest Common Divisor

Asked By: Viveka    Date: May 30    Category: Java    Views: 709

I have to write a program to find the Greatest Common
Divisor of two integers. For example, the GCD of 24 and 16 is 8.
Euclid's method of finding GCDs went like this (it is one of the
oldest algorithms extant):

For two integers p and q:
a) if q divides exactly into p then the result is q
b) set r = remainder of p divided by q
c) set p = q and q = r
d) repeat from stage a)

I have to use the JOptionPane.showInputDialog() function to input two
strings and convert them to integers.

What i have so far is below, which is made up of my limited knowledge
as i have just started java and a couple of things i found on the
internet.

/* Generated by Together */
import javax.swing.*;

public class AssessedProg1 {
public static void main (String args[]) {
String strP, strQ, strR;
int intP, intQ, intR;
strP = JOptionPane.showInputDialog("Enter a value for P: ");
intP = Integer.parseInt(strP);
strQ = JOptionPane.showInputDialog("Enter a value for Q: ");
intQ = Integer.parseInt(strQ);
}
}

public static int GCD(int a, int b) {
int intP = a, intQ = b;
while (intP % intQ !=0) {
int intR = intP % intQ;
intP = intQ; intQ = intR;
}
Return intQ;
}

if anyone can offer the slightest bit of help i would be very
grateful.

Share:

the GCD method  has to be a recursive method ( use GCD within a GCD method).

public int  GCD(int a, int b) {
int intP = a, intQ = b;
while (intP % intQ !=0) {
int intR = intP % intQ;
intP = intQ; intQ = intR;
}
Return GCD ( intP, intQ);
}

and I do not think the method has to be static  method.

Didn't find what you were looking for? Find more on Greatest Common Divisor Or get search suggestion and latest updates.