Advertisement
dimipan80

Greatest Common Divisor of Given Two Integers

Aug 9th, 2014
272
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.88 KB | None | 0 0
  1. /* Write a program that calculates the greatest common divisor (GCD)
  2.  * of given two integers a and b. Use the Euclidean algorithm. */
  3.  
  4. import java.util.Scanner;
  5.  
  6. public class _17_CalculateGreatestCommonDivisorOfGiven2Integers {
  7.  
  8.     public static void main(String[] args) {
  9.         // TODO Auto-generated method stub
  10.         Scanner scan = new Scanner(System.in);
  11.         System.out.print("Enter a 2 Integer numbers: ");
  12.         int numA = scan.nextInt();
  13.         int numB = scan.nextInt();
  14.         scan.close();
  15.  
  16.         numA = Math.abs(numA);
  17.         numB = Math.abs(numB);
  18.  
  19.         if (numA != numB) {
  20.             if (numB > numA) {
  21.                 numA += numB;
  22.                 numB = numA - numB;
  23.                 numA -= numB;
  24.             }
  25.  
  26.             // Using Euclidean algorithm:
  27.             while (numB > 0) {
  28.                 int remaider = numA % numB;
  29.                 numA = numB;
  30.                 numB = remaider;
  31.             }
  32.         }
  33.  
  34.         System.out.println("The Greatest common Divisor of these 2 numbers is: "
  35.                         + numA);
  36.     }
  37.  
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement