Friday, December 22, 2017

Java Euclidean algorithm (finding GCD / HCF)


import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Solution {
    public static void main(String[] args) throws Exception {

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        try
        {
            int i1 = Integer.parseInt(bufferedReader.readLine());
            i1 = Math.abs(i1);
            int i2 = Integer.parseInt(bufferedReader.readLine());
            i2 = Math.abs(i2);
            int gcd = 0;
            while (true)
            {
                if (i1 > i2)
                {
                    if (i1 % i2 == 0)
                    {
                        gcd = i2;
                        break;
                    } else {
                        i1 = i1 % i2;
                    }
                }
                else if (i2 > i1)
                {
                    if (i2 % i1 == 0)
                    {
                        gcd = i1;
                        break;
                    } else {
                        i2 = i2 % i1;
                    }
                }
                System.out.println("i1 = " + i1 + " / i2 = " + i2);
            }
            System.out.println(gcd);
        } catch (Exception e)
        {
            throw e;
        }
    }
}

No comments:

Post a Comment