Ads

The greatest common divisor of two integers 16 and 24 is 8.

Develop the algorithm for finding the greatest common divisor of two numbers. Write a program that prompts the user to enter two integers and calculates the GCD for the entered numbers.

Develop the algorithm for finding the greatest common divisor of two numbers. Write a program that prompts the user to enter two integers and calculates the GCD for the entered numbers.

Ads

View Answers

March 3, 2010 at 11:46 AM

Hi Friend,

Try the following code:

import java.util.*;

class GCD{

public static int determineGCD(int a, int b) {

if (b==0)

return a;

else

return determineGCD(b, a % b);

}

public static void main(String[] args)throws Exception {

GCD cal = new GCD();

Scanner input=new Scanner(System.in);

System.out.println("Enter first number: ");

int num1=input.nextInt();

System.out.println("Enter second number: ");

int num2=input.nextInt();

int gcd = cal.determineGCD(num1, num2);

System.out.println("GCD of two numbers= "+gcd);

}

}

Thanks

Try the following code:

import java.util.*;

class GCD{

public static int determineGCD(int a, int b) {

if (b==0)

return a;

else

return determineGCD(b, a % b);

}

public static void main(String[] args)throws Exception {

GCD cal = new GCD();

Scanner input=new Scanner(System.in);

System.out.println("Enter first number: ");

int num1=input.nextInt();

System.out.println("Enter second number: ");

int num2=input.nextInt();

int gcd = cal.determineGCD(num1, num2);

System.out.println("GCD of two numbers= "+gcd);

}

}

Thanks

Ads

Related Tutorials/Questions & Answers: