Kotlin: Euclidean Algorithm


I wrote Euclidean Algorithm in Kotlin.

Euclidean Algorithm

One way to calculate the greatest common measure of 2 natural numbers. It is written in Euclidean Elements.

Example

Let’s calculate the greatest common measure of 46 and 36 with Euclidean Algorithm.

\begin{eqnarray} 46 & = & 36 \times 1 + 10 \\ 36 & = & 10 \times 3 + 6 \\ 10 & = & 6 \times 1 + 4 \\ 6 & = & 4 \times 1 + 2 \\ 4 & = & 2 \times 2 \end{eqnarray}

Thus, the greatest common measure is 2.

Environment

  • Kotlin 1.0.0

Code

Euclidean Algorithm is basically for 2 numbers, but the code I wrote can handle more numbers.

main function calls solve. solve does the calculation.

solve calculate and return the greatest common divisor of the given natural numbers. main prints it to standard out.

When there is no greatest common divisor (no common factors), solve returns 1.

Maybe there is more effective algorithm.

Usage

If you create jar, you can execute it as follows.

Example

Application

Since the greatest common divisor can be obtained, it is possible to simplify fractions.

For example, a class Fraction for fractions can be created as follows. In the initialization process, the denominator and numerator are divided by the greatest common divisor to make it an irreducible fraction. If the denominator (numerator) becomes 1, it becomes an integer.