Greatest Common Divisor in Java
Posted: , Last Updated:
package greatest_common_divisor.java;
/**
* Used to perform the Euclidean Algorithm to find the greatest common divisor (gcd) of two numbers.
* For more than two numbers, e.g. three, you can box it like this: gcd(a,gcd(b,greatest_common_divisor.c)) etc.
*/
public class GreatestCommonDivisor {
/**
* Recursive implementation to find the gcd (greatest common divisor) of two integers using the euclidean algorithm.
* This runs in O(log(n)) where n is the maximum of a and b.
* @param a the first integer
* @param b the second integer
* @return the greatest common divisor (gcd) of the two integers.
*/
public static int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
}
About the algorithm and language used in this code snippet:
Euclidean Greatest Common Divisor (GCD) Algorithm
The greatest common divisor of two numbers (in this case a and b) is the biggest number which both numbers can be divided by without a rest. This greatest common divisor algorithm, called the euclidean algorithm, determines this number. The greatest common divisor is also often abbreviated as gcd.
Description of the Algorithm
The basic principle behind thus gcd algorithm is to recursively determine the gcd of a and b by determining the gcd of b and a % b This hinges on the fact that the gcd of two numbers also divides their difference, e.g. the greatest common divisor of 16 and 24 (which is 8) is also the greatest common divisor of 2416=8. This is therefore also true for 16 and 40  in fact, rather than taking the difference, the remainder can also be used (repeatedly recursing on the difference will inevitable “pass” the remainder). In summary, the euclidean gcd algorithm uses these 2 steps:
 if a or b is 0, return the other one.
 Repeat with the new a as b and the new b as a % b.
Using the remainder has a much faster runtime compared to using the difference.
Example of the Algorithm
When computing the gcd of 1071 and 462, the following steps will be taken:
 a is 1071, new b is 462
 Recursing with new a = b and new b = a % b…
 New a is 462, new b is 147
 Recursing with new a = b and new b = a % b…
 New a is 147, new b is 21
 Recursing with new a = b and new b = a % b…
 New a is 21, new b is 0
 b is 0, stopping recursion, a is the gcd: 21
Runtime Complexity of the Algorithm
The runtime complexity of the Euclidean greatest common divisor algorithm is O(log(max(a,b))) (the logarithm of the maximum of the two numbers). Using the remainder rather than the difference is considerably faster  if the difference would’ve been used this greatest common divisor algorithm would’ve had a runtime of O(max(a,b))
Space Complexity of the Algorithm
The space complexity of the Euclidean greatest common divisor algorithm is equal to the runtime, since every recursive call is saved in the stack and everything else is constant.
Java
Java™ is a compiled language used for many purposes, ranging from embedded systems, UIapplications to web servers.
Getting to “Hello World” in Java
The most important things first  here’s how you can run your first line of code in Java.
 Download and install the latest version of Java from java.com. You can also download an earlier version if your use case requires it.

Open a terminal, make sure the
javac
andjavac
commands are working, and that the command your’re going to be using is referring to the version you just installed by runningjava version
. If you’re getting a “command not found” error (or similar), try restarting your command line, and, if that doesn’t help, your computer. If the issue persists, here are some helpful StackOverflow questions for each platform: 
As soon as that’s working, copy the following snippet into a file named HelloWorld.java:
class HelloWorld { public static void main(String[] args) { // Paste any following code snippets here. System.out.println("Hello World"); } }
 Change directory by typing
cd path/to/HelloWorld
, then runjavac HelloWorld.java
to compile the file (which creates the bytecode), then runjava HelloWorld
(without the .java ending). This should print “Hello World” to your Terminal.
That’s it! Notice that the entry barrier is a little higher with Java than it is with e.g. Python  but Java is much faster and, in my experience, tends to have fewer bugs in large projects due to strong typing and other factors.
Fundamentals in Java
To understand algorithms and technologies implemented in Java, one first needs to understand what basic programming concepts look like in this particular language. Each of the following snippets should be surrounded by the boilerplate code of the hello world example and should be compiled and run using the commands mentioned above.
Variables and Arithmetic
Variables in Java are statically typed, meaning the content of a variable needs to be specified when writing the code.
The datatype for whole numbers, for example is int
.
Numbers with decimal places are typed float
or double
depending on the required precision.
The type for text ist String
.
int number = 5;
double decimalNumber = 3.25;
double result = number * decimalNumber;
String callout = "The number is ";
// In this instance, the values are concatenated rather than added because one of them is a String.
System.out.println(callout + result);
Arrays
Arrays in Java are real arrays (as opposed to e.g. Python where they’re implemented as lists). The implications of that are that the size needs to be set when they are created and cannot be changed, but also that they are more efficient in Java than they are in Python.
int[] integers = new int[5];
integers[3] = 12; // Assigning values to positions in the array
// integers[4] is 0, integers[6] would give IndexOutOfBoundsException
String[] strings = {"Hello", "World"}; // Array initialization with initial values
System.out.println(strings[0] + integers[3]); // Prints "Hello12"
Conditions
Just like most programming languages, Java can do ifelse
statements. Additionally, Java can also do switchcase
statements.
int value = 5;
if(value == 5){
System.out.println("Value is 5");
} else if(value < 5){
System.out.println("Value is less than 5");
} else {
System.out.println("Value is something else");
}
switch (value){
case 1:
System.out.println("Value is 1");
break; // Don't go further down the cases
case 2:
System.out.println("Value is 2");
break; // Don't go further down the cases
case 3:
System.out.println("Value is 3");
break; // Don't go further down the cases
case 4:
System.out.println("Value is 4");
break; // Don't go further down the cases
case 5:
System.out.println("Value is 5");
break; // Don't go further down the cases
default:
System.out.println("Value is something else");
}
The above Java code will print “Value is 5” twice.
Loops
Java supports for
, while
as well as do while
loops. break
and continue
statements are also supported.
The below example illustrates the differences:
int value = 2;
for (int i = 0; i < value; i++) {
System.out.println(i);
}
while (value > 0) {
System.out.println(value);
value;
}
do {
System.out.println(value);
value;
} while (value > 0);
This will print the following to the terminal:
0
1
2
1
0
Note the last 0
: it is printed because in the dowhile
loop, compared to the while
loop. the code block is executed at least once before the condition is checked.
Functions
Functions in Java can be part of a class, or of an object of a class. For more information on object oriented programming I recommend the w3schools course. Here is a minimal example of a function as part of a class (also called a static function):
class HelloWorld {
public static void main(String[] args) {
System.out.println(addNumbers(3, 4));
}
public static int addNumbers(int numberOne, int numberTwo) {
return numberOne + numberTwo;
}
}
And here’s an example of calling a function of an object of a class:
class HelloWorld {
public static void main(String[] args) {
System.out.println(new HelloWorld().addNumbers(3, 4));
}
public int addNumbers(int numberOne, int numberTwo) {
return numberOne + numberTwo;
}
}
Note how the first example uses the static
keyword, and the second example needs to instantiate on object of the class before in can call the function of that object.
These are some of the differences in class methods and object functions.
Syntax
Java requires the use of curly brackets ({}
) to surround code blocks in conditions, loops, functions etc.;
It also requires semicolons at then end of statements.
While this can lead to some annoying syntax errors, it also means the use of whitespace for preferred formatting (e.g. indentation of code pieces) does not affect the code.
Advanced Knowledge of Java
Java was first released in 1995 and is multiparadigm, meaning while it is primarily objectoriented, it also has functional and reflective elements. It’s statically typed, but offers some amount of dynamic typing in recent versions. For more information, Java has a great Wikipedia) article.