206k views
3 votes
The greatest common divisor of integers x and y is the largest integer that evenly divides into both x and y. Write a recursive method gcd that returns the greatest common divisor of x and y. The gcd of x and y is defined recursively as follows: If y is equal to 0 then gcd(x,y) is x; otherwise gcd(x,y) is gcd(y,x%y), where % is the remainder operator

User Alecxs
by
5.3k points

1 Answer

3 votes

Answer:this is made in java programing language

Program:

/**********************************************************

* The following GreatestCommonDivisor class demonstrates *

* a method called gcd. It reads two integers from the user*

* and displays the GCD of two integers. The method gcd *

* calculates and returns the GCD of two integers. *

**********************************************************/

// GreatestCommonDivisor class

import java.util.Scanner;

public class GreatestCommonDivisor

{

// start main main method

public static void main(String[] args)

{

// declare variables

int firstInteger;

int secondInteger;

int gcdOfTwoIntegers;

// create an object for Scanner class

Scanner input = new Scanner(System.in);

Prompt the user to enter the two positive integers.

// prompt the user to enter the first integer

System.out.print("Enter the first positive integer: ");

firstInteger = input.nextInt();

// prompt the user to enter the second integer

System.out.print("Enter the second positive integer: ");

secondInteger = input.nextInt();

Call the gcd method to get the greatest common divisor of two integers.

// call gcd method to get gcd of two integers

gcdOfTwoIntegers =

gcd(firstInteger, secondInteger);

Display the greatest common divisor of two integers.

// display the gcd of two integers

System.out.println("The GCD of " + firstInteger + " and " + secondInteger +

" is " + gcdOfTwoIntegers);

} // end of main method

The following gcd method accepts two integers as its parameters. It finds and returns the greatest common divisor of these integers recursively.

// gcd method implementation

public static int gcd(int x, int y)

{

// verify whether the value of y is zero or not

if(y == 0)

// return x if the value of y is zero

return x;

else

/* call gcd method recursively if the value of y is non-zero */

return gcd(y, x % y);

} // end of gcd method

} // end of GreatestCommonDivisor class

Step-by-step explanation:

User Tysean
by
4.5k points