m2skills

gcdEuclid java

May 23rd, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.10 KB | None | 0 0
  1. // program to find the gcd of 2 numbers using euclids algorithm
  2. import java.util.Scanner;
  3.  
  4. public class findGcd{
  5.     public static void main(String arg[]){
  6.        
  7.         boolean cont = true;
  8.         int number1, number2, answer;
  9.         Scanner sc = new Scanner(System.in);
  10.         while(cont){
  11.             System.out.print("\nEnter the first number : ");
  12.             number1 = sc.nextInt();
  13.            
  14.             System.out.print("Enter the second number : ");
  15.             number2 = sc.nextInt();
  16.            
  17.             answer = gcd(number1, number2);
  18.             System.out.println("The gcd of " + number1 + " and " + number2 + " is : " + answer);
  19.            
  20.             System.out.print("\nDo you want to continue : ");
  21.             int n = sc.nextInt();
  22.             if(n == 0){
  23.                 cont = false;
  24.             }
  25.         }
  26.     }  
  27.        
  28.     static int gcd(int num1, int num2){
  29.         int temp,quotient;
  30.         if(num1>num2)
  31.         {
  32.             do
  33.             {
  34.                 quotient = num1 / num2;
  35.                 temp = num2;
  36.                 num2 = num1 - quotient * num2;
  37.                 num1 = temp;
  38.             }while(num2!=0);
  39.             return num1;
  40.         }
  41.         else
  42.         {
  43.             do
  44.             {
  45.                 quotient = num2 / num1;
  46.                 temp = num1;
  47.                 num1 = num2 - quotient * num1;
  48.                 num2 = temp;
  49.             }while(num1!=0);
  50.             return num2;
  51.         }
  52.     }
  53.  
  54. }
Add Comment
Please, Sign In to add comment