Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to write a simple Java program that finds the greatest common divisor between two numbers?
    primarykey
    data
    text
    <p>Here is the question:</p> <p>"Write a method named gcd that accepts two integers as parameters and returns the greatest common divisor of the two numbers. The greatest common divisor (GCD) of two integers a and b is the largest integer that is a factor of both a and b. The GCD of any number and 1 is 1, and the GCD of any number and 0 is that number.</p> <p>One efficient way to compute the GCD of two numbers is to use Euclid's algorithm, which states the following:</p> <pre><code>GCD(A, B) = GCD(B, A % B) GCD(A, 0) = Absolute value of A" </code></pre> <p>I'm really confused as to how to solve this problem. I just want some hints and tips as to what I did wrong in the program I have so far. (I have to put in a Scanner, that is my teacher's requirement.) Don't give me a full code as I kinda want to solve this out myself. Maybe just give me a hint on how I incorporate this formula that you see above. (And if you're wondering why I put in the == 0, it's because I thought that if you have two numbers, say 0 and 90, their GCD would be 0 right??)</p> <p>Also, my code has to include while loops...I would've preferred if loops...</p> <p>Thanks in advance! :)</p> <p>My current program:</p> <pre><code>public static void main(String[] args) { Scanner console = new Scanner(System.in); int a = console.nextInt(); int b = console.nextInt(); gcd (a, b); } public static void gcd(int a, int b) { System.out.print("Type in two numbers and I will print outs its Greatest Common Divisor: "); int gcdNum1 = console.nextInt(); int gcdNum2 = console.nextInt(); while (gcdNum1 == 0) { gcdNum1 = 0; } while (gcdNum2 &gt; gcdNum1) { int gcd = gcdNum1 % gcdNum2; } System.out.print(gcdNum1 + gcdNum2); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload