I tried to implement the Euclidean algorithm in Java

What is Euclidean algorithm?

An algorithm that finds the greatest common divisor of two natural numbers.

To put it simply

a % b = r
b % r = s
r % s = 0

The number to be divided is the next number to be divided, and the remainder is the next number to be divided, and this is repeated recursively. The number to divide when the remainder becomes 0 (s in the above example) is the greatest common divisor of the natural numbers a and b.

reference Euclidean algorithm and indefinite equation | Beautiful story of high school mathematics

I tried to implement

package com.company;

import java.io.*;

class Main {
    public static void main(String[] args) {
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            String[] str = bufferedReader.readLine().split(" ");
            int x = Integer.parseInt(str[0]);
            int y = Integer.parseInt(str[1]);

            System.out.println(getCommonDivisor(x, y));

        } catch (Exception e) {
            System.out.println(e);
        }
    }

    private static int getCommonDivisor(int x, int y) {
        int biggerNum = Math.max(x, y);
        int smallerNum = Math.min(x, y);

        //Find the remainder of dividing the smaller one from the larger one
        int surplus = biggerNum % smallerNum;

        //If it is divisible, return it
        if (surplus == 0) {
            return smallerNum;
        }
        //Recursively call confidence if not divisible
        surplus = getCommonDivisor(smallerNum, surplus);

        return surplus;
    }
}

Try out

//input
390 273 

//output
39

Postscript (June 23, 2017)

The above code originally did not think deeply about input etc., just implemented the algorithm, so it does not consider exception handling etc. and it easily falls.

Therefore, I wrote a new code that reflects the comment received from @ saka1029. Thank you, @ saka1029.

This time, the code is written under the following conditions.

With the implementation of Euclidean algorithm, negative numbers are repelled at the entrance.

Even if something other than numbers is entered, it will not drop

In addition, there are schools that include 0 in natural numbers and schools that do not include 0 in natural numbers, but this time, we will adopt the "school that does not include 0 in natural numbers".

Exception handling code

package com.company;

import java.io.*;

class Main {
    private static int x = -1;
    private static int y = -1;
    private static final String caution = "Please enter two natural numbers separated by half-width spaces.(However, 0 is not naturally included in this program.)";

    public static void main(String[] args) {
        System.out.println(caution);
        readInput();
        System.out.println(doEuclideanAlgorithm(x, y));
    }

    private static void readInput() {
        try {
            while (x <= 0 || y <= 0) {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
                String[] str = bufferedReader.readLine().split(" ");
                x = Integer.parseInt(str[0]);
                y = Integer.parseInt(str[1]);
                if (x <= 0 || y <= 0) {
                    System.out.println("The input is incorrect." + caution);
                }
            }
        } catch (Exception e) {
            System.out.println("The input is incorrect." + caution);
            readInput();
        }
    }

    private static int doEuclideanAlgorithm(int x, int y) {
        int biggerNum = Math.max(x, y);
        int smallerNum = Math.min(x, y);

        //Find the remainder of dividing the smaller one from the larger one
        int surplus = biggerNum % smallerNum;

        //If it is divisible, return it
        if (surplus == 0) {
            return smallerNum;
        }
        //Recursively call confidence if not divisible
        surplus = doEuclideanAlgorithm(smallerNum, surplus);

        return surplus;
    }
}

I've tried

Please enter two natural numbers separated by half-width spaces.(However, 0 is not naturally included in this program.)
a a
The input is incorrect. Please enter two natural numbers separated by half-width spaces.(However, 0 is not naturally included in this program.)
390 0
The input is incorrect. Please enter two natural numbers separated by half-width spaces.(However, 0 is not naturally included in this program.)
0 273 
The input is incorrect. Please enter two natural numbers separated by half-width spaces.(However, 0 is not naturally included in this program.)
-390 273
The input is incorrect. Please enter two natural numbers separated by half-width spaces.(However, 0 is not naturally included in this program.)
390 -273
The input is incorrect. Please enter two natural numbers separated by half-width spaces.(However, 0 is not naturally included in this program.)
390 273 
39

Other

If you have something like "It's strange here" or "I can make it smarter", I would appreciate it if you could comment.

Further notes (June 23, 2017)

As you said in @ howdy39's comment, there were some subtleties. Thank you, @ howdy39. Here is the smart code that adopted @ howdy39's point.

I didn't need a while statement because I was recursively executing readInput () when there was an exception.

Implementation

package com.company;

import java.io.*;

class Main {
    private static final String caution = "Please enter two natural numbers separated by half-width spaces.(However, 0 is not naturally included in this program.)";

    public static void main(String[] args) {
        System.out.println(caution);
        int[] inputs = readInput();
        System.out.println(doEuclideanAlgorithm(inputs[0], inputs[1]));
    }

    private static int[] readInput() {
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            String[] str = bufferedReader.readLine().split(" ");
            int x = Integer.parseInt(str[0]);
            int y = Integer.parseInt(str[1]);
            if (x <= 0 || y <= 0) {
                throw new Exception("");
            }
            return new int[]{x, y};
        } catch (Exception e) {
            System.out.println("The input is incorrect." + caution);
            return readInput();
        }
    }

    private static int doEuclideanAlgorithm(int x, int y) {
        int biggerNum = Math.max(x, y);
        int smallerNum = Math.min(x, y);

        //Find the remainder of dividing the smaller one from the larger one
        int surplus = biggerNum % smallerNum;

        //If it is divisible, return it
        if (surplus == 0) {
            return smallerNum;
        }
        //Recursively call confidence if not divisible
        surplus = doEuclideanAlgorithm(smallerNum, surplus);

        return surplus;
    }
}

Execution result

Please enter two natural numbers separated by half-width spaces.(However, 0 is not naturally included in this program.)
a a 
The input is incorrect. Please enter two natural numbers separated by half-width spaces.(However, 0 is not naturally included in this program.)
390 0
The input is incorrect. Please enter two natural numbers separated by half-width spaces.(However, 0 is not naturally included in this program.)
0 273 
The input is incorrect. Please enter two natural numbers separated by half-width spaces.(However, 0 is not naturally included in this program.)
-390 273
The input is incorrect. Please enter two natural numbers separated by half-width spaces.(However, 0 is not naturally included in this program.)
390 -273
The input is incorrect. Please enter two natural numbers separated by half-width spaces.(However, 0 is not naturally included in this program.)
390 273
39

The site that I used as a reference

Euclidean algorithm and indefinite equation | Beautiful story of high school mathematics

Recommended Posts

I tried to implement the Euclidean algorithm in Java
I tried to implement deep learning in Java
I tried to implement Firebase push notification in Java
Implement the algorithm in Ruby: Day 1 -Euclidean algorithm-
I tried the new era in Java
I tried to implement the Iterator pattern
I tried to implement polymorphic related in Nogizaka.
I tried to organize the session in Rails
I tried to output multiplication table in Java
I tried to create Alexa skill in Java
I tried metaprogramming in Java
I tried to organize the cases used in programming
I tried to implement TCP / IP + BIO with JAVA
# 2 [Note] I tried to calculate multiplication tables in Java.
I tried to create a Clova skill in Java
I tried to make a login function in Java
I tried to implement Stalin sort with Java Collector
[Java] I tried to implement Yahoo API product search
~ I tried to learn functional programming in Java now ~
I tried to find out what changed in Java 9
I tried to interact with Java
I tried to explain the method
I tried the Java framework "Quarkus"
I tried using JWT in Java
I tried to summarize Java learning (1)
Try to implement Yubaba in Java
I tried to summarize Java 8 now
I tried to implement the like function by asynchronous communication
[JDBC] I tried to access the SQLite3 database from Java.
I tried to summarize the basics of kotlin and java
[Swift] I tried to implement the function of the vending machine
I tried to convert a string to a LocalDate type in Java
I tried using Dapr in Java to facilitate microservice development
I tried to implement a buggy web application in Kotlin
I tried to make a client of RESAS-API in Java
I want to simplify the conditional if-else statement in Java
I tried using Elasticsearch API in Java
I tried to summarize the words that I often see in docker-compose.yml
How to implement Kalman filter in Java
I tried to summarize the methods used
I finished watching The Rose of Versailles, so I tried to reproduce the ending song in Java
I tried to illuminate the Christmas tree in a life game
Java reference to understand in the figure
Try to implement n-ary addition in Java
I tried to sort the data in descending order, ascending order / Rails
I tried to implement the image preview function with Rails / jQuery
I tried setting Java beginners to use shortcut keys in eclipse
I tried to translate the error message when executing Eclipse (Java)
How to get the date in java
I tried to summarize the Stream API
I tried to summarize the methods of Java String and StringBuilder
I tried the AutoValue library in Intellij
[Java] I want to perform distinct with the key in the object
I tried to move the Java compatible FaaS form "Fn Project"
I tried to display the calendar on the Eclipse console using Java.
I tried to implement ModanShogi with Kinx
[Introduction to Java] I tried to summarize the knowledge that I think is essential
I tried to solve the tribonacci sequence problem in Ruby, with recursion.
I called the COTOHA API parser 100 times in Java to measure performance.
I want to get the IP address when connecting to Wi-Fi in Java
I tried to make a talk application in Java using AI "A3RT"