Greatest Common Denominator/Divisor/Factor (Geek Style — Euclidean Algorithm)

import java.util.Scanner;

/**
* Created by James Shinevar on 6/10/17.
* james.shinevar@gmail.com
* http://jamesshinevar.com
*/
public class GCDMain {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter your first number:");
long FirstNumber = input.nextLong();
input.nextLine();
System.out.println("Please enter your second number:");
long SecondNumber = input.nextLong();
input.nextLine();
System.out.println("SlowGCD is: " + SlowGCD(FirstNumber,SecondNumber));
}

private static long SlowGCD(long FirstNumber, long SecondNumber) {
long GCD = 0;

for (long counter = 1; counter < (FirstNumber + SecondNumber); counter++) {
if (FirstNumber % counter == 0) {
if (SecondNumber % counter == 0) {
GCD = counter;
}
}
}
return GCD;
}
}
import java.util.Scanner;
/**
* Created by James Shinevar on 6/10/17.
* james.shinevar@gmail.com
* http://jamesshinevar.com
*/
public class GCDMain {

public static long FinalGCD;

{
FinalGCD = 0;
}

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter your first number:");
long FirstNumber = input.nextLong();
input.nextLine();
System.out.println("Please enter your second number:");
long SecondNumber = input.nextLong();
input.nextLine();
FastGCD(FirstNumber, SecondNumber);
System.out.println("FastGCD is: " + FinalGCD);
}

private static void FastGCD(long FirstNumber, long SecondNumber) {
if (SecondNumber > FirstNumber) {
long largerNumber = SecondNumber;
SecondNumber = FirstNumber;
FirstNumber = largerNumber;
}
if (FirstNumber == 0) {
FinalGCD = SecondNumber;
} else if (SecondNumber == 0) {
FinalGCD = FirstNumber;
} else {
long ModulusResult = FirstNumber % SecondNumber;
FirstNumber = SecondNumber;
SecondNumber = ModulusResult;
FastGCD(FirstNumber, SecondNumber);
}
}
}

References

Euclidean algorithm. (2017). Sites.math.rutgers.edu. Retrieved 10 June 2017, from http://sites.math.rutgers.edu/~greenfie/gs2004/euclid.html

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store