Answer to Question #259150 in Java | JSP | JSF for joy

Question #259150

6. The GCD



by CodeChum Admin




The greatest common divisor, also known as GCD, is the greatest number that will, without a remainder, fully divide a pair of integers.






Now, I want you to make a program that will accept two integers and with the use of loops, print out their GCD. Make good use of conditional statements as well.




Off you go!




Input




A line containing two integers separated by a space.




6·9



Output




A line containing an integer.




3

1
Expert's answer
2021-11-02T13:08:43-0400
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();
        System.out.println(gcd(a,b));
        sc.close();
    }

    private static int gcd(int a, int b) {
        int c;
        while(a!=0 && b!=0)
        {
            c = b;
            b = a%b;
            a = c;
        }
        return a+b;
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS