I have made an implementation of the Euclidean algorithm in Java, following the pseudocode shown below.
As far as my knowledge goes, I can't find a way of making this more efficient.
I have looked into other peoples implementations of this algorithm and there are a few which are slightly shorter, and some that use recursion.
The pseudocode:
function gcd(a, b)
while b ≠ 0
t := b
b := a mod b
a := t
return a
My implementation:
import java.util.Scanner;
public class EuclideanAlgorithm {
public static void main (String [] args) {
int a, b;
try(Scanner sc = new Scanner(System.in);) {
System.out.print("Enter integer a: ");
a = sc.nextInt();
System.out.print("Enter integer b: ");
b = sc.nextInt();
}
long start = System.nanoTime();
int answer = EuclideanAlgorithm(a, b);
long stop = System.nanoTime();
System.out.println("gcd = " + answer);
System.out.println("Execution time: " + ((stop - start) / 1e+6) + "ms.");
}
public EuclideanAlgorithm() {}; //Suppress default constructor
private static int EuclideanAlgorithm(int a, int b) {
int t;
while (b != 0) {
t = b;
b = a % b;
a = t;
}
return a;
}
}
Is there a way to make this implementation more efficient, and would it have been more efficient to use recursion?