Skip to content

Exercise_07_14 Alternative Solution #7

Open

Description

@SquirrelCoder

Hi,

so I was working on this exercise, after I wrote it, I checked with your code, and I think it's a little bit complicated, I searched for GCD, and apparently Euclidean algorithm works much better and is faster too.
So I thought, I should implement it.
Here is my code, if you like, you can add my solution this solution (:D) as an alternative solution too :).

Thanks a lot.

public class Num_14_Euclid_Algo {
    public static void main(String[] args) {
        java.util.Scanner input = new java.util.Scanner(System.in);
        int[] userNumbers = new int[5];

        for (int i = 0; i < userNumbers.length; i++) {
            userNumbers[i] = input.nextInt();
        }

        System.out.println("GCD is: " + gcdOfMultipleNumbers(userNumbers));

    }

    public static int euclidAlgorithm(int a, int b) {
        int remainder = a % b;
        int quotient = 0;
        while (remainder != 0) {
            a = b;
            b = remainder;
            remainder = a % b;
            quotient = b;
        }
        return quotient;
    }

    public static int gcdOfMultipleNumbers(int... array) {
        int gcd = array[0];
        for (int i = 1; i < array.length; i++) {
            gcd = euclidAlgorithm(gcd, array[i]);
        }
        return gcd;
    }
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions