Search code examples
javamathprintingnumbersgreatest-common-divisor

I made code to calculate greatest common divisor but there is issue


Hi people I made code to calculate greatest common divisor of 2 number.

It work good but I get many outputs. I want the greatest output but I don't know how to fix it?

What my code do is this here: You enter 2 integer. The first integer must be greater than the second. Now code check second integer first. Is it dividable by 1, 2, 3, 4, 5, .. Then code check all working numbers with first number. In the end we have greatest common divisor.

And before code does all it, it check if second number divide first (in case second is the gcd).

Now my problem: Let's take input 36 and 14. My code will give output

1
2

But how can I avoid code also print all other working numbers? I only want printed the greatest working number but no idea how to implement this in my code? I also don't want copy other code because I did all myself till here and proud:

import java.util.Scanner;

public class Testit{

    public static void main(String[] args){

        Scanner input = new Scanner(System.in);
        double x = input.nextDouble();
        double y = input.nextDouble();
        double first=0;

        first=x/y;

        if(first==(int)first){
            System.out.println((int)y);
            return;
        }

        else{
            for(double i=1; i<x && i<y; i++){
                double sum=0;
                sum=y/i;

                if(sum==(int)sum){
                    double temp=0;
                    temp=x/i;
                    if(temp==(int)temp){
                        System.out.println((int)i);
                    }
                }
            }
        }
    }
}

Solution

  • Instead of printing, save the result in a temporary variable

    double first=0;
    int greatestCommonDivisor = 1;
    ...
                    if(temp==(int)temp){
                        greatestCommonDivisor = Double.valueOf(i).intValue();
                    }
    ...
    System.out.println("Greatest common divisor:" + greatestCommonDivisor);
    

    That said, there are a lot of places your algorithm and code could be improved. For a start you should think about starting at the largest possible number and just stopping when you found the first common divisor (because that would be the greatest) instead of looping through all possible numbers starting from the smallest possible number. And you should have a look at the modulo operation and use integers instead of doubles for your values.