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

Related Tutorials/Questions & Answers:

Ads

- Java Tutorials
- Java Code example
- Java Programming
- Java Beginners Examples
- Applet Tutorials
- Awt Tutorials
- Java Certification
- Interview Question
- Java Servlets Tutorial
- Jsp Tutorials
- Java Swing Tutorials
- JDBC Tutorial
- EJB Tutorials
- Java Server Faces (JSF) Tutorial
- WAP Tutorial
- Struts Tutorial
- JAXB Tutorial
- Spring FrameWork Tutorial
- SOA&Web Services Tutorials
- Bioinformatics Tutorials
- MySQL Tutorials
- JAVA DOM Tutorial
- XML Tutorial
- EAI Articles
- Many Programming Tutorials Links
- Tutorials Books
**Java Script Tutorial****Ajax Tutorial****Dojo Tutorials****Programming Books****Trainings****Flex****Ant****RDF**