Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Exercise_07_14 Alternative Solution #7

Open
SquirrelCoder opened this issue Feb 9, 2017 · 0 comments
Open

Exercise_07_14 Alternative Solution #7

SquirrelCoder opened this issue Feb 9, 2017 · 0 comments

Comments

@SquirrelCoder
Copy link

SquirrelCoder commented Feb 9, 2017

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;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant