Skip to content

Instantly share code, notes, and snippets.

@pajuey
Created January 30, 2013 05:20
Show Gist options
  • Save pajuey/4670856 to your computer and use it in GitHub Desktop.
Save pajuey/4670856 to your computer and use it in GitHub Desktop.
/**
* GCD.java
* Steven Pajuelo
* spajuelo
* pa3
* Make a GCD to find GCD for two integer types, which neither are negative or of another type.
*/
import java.util.Scanner;
public class GCD2{
private static int number, divisor, dividend, gcd;
private static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
// Ask for dividend
System.out.print("Enter a positive integer: ");
int count = 0;
while(true){
// discard non-int types
if(!scan.hasNextInt()){
checkType(scan);
continue;
}
// discard negative integers
else{
number = scan.nextInt();
if(number<0){
System.out.print("Please enter a positive number: ");
continue;
}else{
// save positive integers, assign dividend to 0, and divisor to 1
if(count==0){
dividend = number;
}else{
divisor = number;
break;
}
} // end nested if-statement.
} // end main if-statement. Continue ends here.
count++;
System.out.print("Enter another integer: ");
} // end while loop. Break ends here.
System.out.print("GCD of " + dividend + " and " + divisor + " is " + computeGCD() + ".");
}
// method for computer gcd
static int computeGCD() {
while (divisor != 0) {
int temp = divisor;
divisor = dividend % divisor;
dividend = temp;
gcd = dividend;
}
return gcd;
}
static void checkType(Scanner scan) {
System.out.print("Please enter a positive 'integer': ");
scan.next();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment