Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner; // for user input
- public class GreatestCommonDivisor {
- public static void main(String[] args) {
- /**
- * Program: GreatestCommonDivisor.java
- * Purpose: Find greatest common divisor of two numbers
- * Creator: Chris Clarke
- * Created: 07.11.2012
- */
- int a = 0, b = 0; // the 2 numbers input
- int c; // the answer
- a = getNumber("Enter your first positive integer: ");
- b = getNumber("Enter your second positive integer: ");
- c = getGreatestCommonDivisor( a, b);
- System.out.println("The greatest common divisor of "+a+" and "+b+" is "+c);
- } // end main
- public static int getNumber(String prompt) {
- int n = 0;
- Scanner scan = new Scanner(System.in);
- System.out.print(prompt);
- try {
- n = scan.nextInt();
- } catch (Exception e) {
- System.out.println("That\'s not an integer!");
- System.exit(1);
- }
- if (n <= 0) {
- System.out.println("That\'s not positive!");
- System.exit(1);
- }
- return n;
- } // end getNumber
- public static int getGreatestCommonDivisor(int a, int b) {
- int gcd = 0;
- int limit = a >= b? a: b; // set limit to a or b, whichever is the greater
- for (int i = 1; i <= limit; i++) {
- if (a % i == 0 && b % i == 0) {
- gcd = i;
- }
- }
- return gcd;
- } // end getGreatestCommonDivisor
- } // end class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement