In: Computer Science
Using Java
The C expression m % n yields the remainders of m divided by n. Define the greatest common divisor (GCD) of two integers x and y by:
gcd(x, y) = y | if (y <= x && x % y == 0) |
gcd(x, y) = gcd(y, x) | if (x < y) |
gcd(x, y) = gcd(y, x % y) | otherwise |
You will submit a program listing (properly commented) and the output using the following data sets:
x | y |
---|---|
32 | 8 |
24 | 15 |
64 | 48 |
import java.lang.*;
import java.util.Scanner;
public class GCD
{
//gcd method using recursion
public static int gcd(int n1, int n2)
{
if (n2 != 0) //recursively call to gcd
return gcd(n2, n1 % n2);
else
return n1;//return n1
}
//driver program
public static void main(String args[])
{
int x,y,g;
//declare scanner object
Scanner scnr = new Scanner(System.in);
//input two numbers
System.out.println("Enter two numbers");
x = scnr.nextInt();
y = scnr.nextInt();
//condition for gcd when y=0
if(y<=x && x%y==0)
g=y;
else
if(x<y) //when x<y
g=gcd(y,x);
else //call gcd when x>y
g=gcd(y,x%y);
//print the GCD
System.out.println("G.C.D of "+x+" and "+y+" is "+g);
}
}
OUTPUT
OR
import java.lang.*;
import java.util.Scanner;
public class GCD
{
//gcd method using recursion
public static int gcd(int n1, int n2)
{
if (n2 != 0) //recursively call to gcd
return gcd(n2, n1 % n2);
else
return n1;//return n1
}
//driver program
public static void main(String args[])
{
int x=32,y=8,g;
//condition for gcd when y=0
if(y<=x && x%y==0)
g=y;
else
if(x<y) //when x<y
g=gcd(y,x);
else //call gcd when x>y
g=gcd(y,x%y);
//print the GCD
System.out.println("G.C.D of "+x+" and "+y+" is "+g);
//set the values of x and y to second data set
x=24;
y=15;
//condition for gcd when y=0
if(y<=x && x%y==0)
g=y;
else
if(x<y) //when x<y
g=gcd(y,x);
else //call gcd when x>y
g=gcd(y,x%y);
//print the GCD
System.out.println("G.C.D of "+x+" and "+y+" is "+g);
//set the values of x and y to third data set
x=64;
y=48;
//condition for gcd when y=0
if(y<=x && x%y==0)
g=y;
else
if(x<y) //when x<y
g=gcd(y,x);
else //call gcd when x>y
g=gcd(y,x%y);
//print the GCD
System.out.println("G.C.D of "+x+" and "+y+" is "+g);
}
}
OUTPUT