Monday, September 12, 2016

JAVA HOW TO PROGRAM, NINTH EDITION, DEITEL: CHAPTER SIX SOLUTIONS



Question: Greatest Common Divisor

The greatest common divisor (GCD) of two integers is the largest integer that evenly divides each of the two numbers. Write a method gcd that returns the greatest common divisor of two integers. [Hint: You might want to use Euclid’s algorithm. You can find information about it at en.wikipedia.org/wiki/Euclidean_algorithm.] Incorporate the method into an application that reads two values from the user and displays the result. 

  

Solution: Greatest Common Divisor

 // Author: Free Coder
//www.freecoder247.blogspot.com

public class GCDExample {
 
public static void main(String args[]){
   
//Enter two number whose GCD needs to be calculated.    
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter first number to find GCD");
int number1 = scanner.nextInt();
System.out.println("Please enter second number to find GCD");
int number2 = scanner.nextInt();
    
System.out.println("GCD of two numbers " + number1 +" and " + number2 +" is :" + findGCD(number1,number2));
}

private static int findGCD(int number1, int number2) {
//base case
if(number2 == 0){
return number1;
}
return findGCD(number2, number1%number2);
}
 
}

No comments:

Post a Comment