Advertisement
brilliant_moves

GreatestCommonDivisor.java

Nov 7th, 2012
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.32 KB | None | 0 0
  1. import java.util.Scanner;   // for user input
  2.  
  3. public class GreatestCommonDivisor {
  4.  
  5.     public static void main(String[] args) {
  6.  
  7.         /**
  8.         *   Program:    GreatestCommonDivisor.java
  9.         *   Purpose:    Find greatest common divisor of two numbers
  10.         *   Creator:    Chris Clarke
  11.         *   Created:    07.11.2012
  12.         */
  13.  
  14.         int a = 0, b = 0;   // the 2 numbers input
  15.         int c;          // the answer
  16.  
  17.         a = getNumber("Enter your first positive integer: ");
  18.         b = getNumber("Enter your second positive integer: ");
  19.  
  20.         c = getGreatestCommonDivisor( a, b);
  21.  
  22.         System.out.println("The greatest common divisor of "+a+" and "+b+" is "+c);
  23.     } // end main
  24.  
  25.     public static int getNumber(String prompt) {
  26.         int n = 0;
  27.         Scanner scan = new Scanner(System.in);
  28.         System.out.print(prompt);
  29.         try {
  30.             n = scan.nextInt();
  31.         } catch (Exception e) {
  32.             System.out.println("That\'s not an integer!");
  33.             System.exit(1);
  34.         }
  35.  
  36.         if (n <= 0) {
  37.             System.out.println("That\'s not positive!");
  38.             System.exit(1);
  39.         }
  40.         return n;
  41.  
  42.     } // end getNumber
  43.  
  44.     public static int getGreatestCommonDivisor(int a, int b) {
  45.         int gcd = 0;
  46.         int limit = a >= b? a: b;   // set limit to a or b, whichever is the greater
  47.  
  48.         for (int i = 1; i <= limit; i++) {
  49.             if (a % i == 0 && b % i == 0) {
  50.                 gcd = i;
  51.             }
  52.         }
  53.  
  54.         return gcd;
  55.  
  56.     } // end getGreatestCommonDivisor
  57. } // end class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement