How does Increment operator work in Java?

In Java; If I'm trying to find the GCD of 2 int's do i do [Largest] % [Smallest] or [Smallest] % [Largest]

  • So I have a Java assignment in which I must write a program to find the GCD(greatest common denominator) of two input numbers. I think I have to use the mod(%) operator to find this but I'm confused on whether I can just do: x mod y or if I have to put either the larger or smaller of the two integers in the (x) place for it to work properly. From my notes I have the following rules that I think need to be true to find the GCD but I can't make sense of them, plus I might just be confusing myself with all this extra stuff: GCD: Can't be largest # Can at most be the smallest # Can't be more than 1/2 of the largest # Any help is appreciated, thanks!

  • Answer:

    You are correct, you will utilize the modulus operator. The basic algorithm is as follows: Given two natural numbers a and b, not both equal to zero: check if b is zero; if yes, a is the GCD. If not, repeat the process using, respectively, b, and the remainder after dividing a by b. And here is it in code: import java.io.*; public class GCD { public static void main(String[] args) throws IOException{ BufferedReader kb =new BufferedReader(new InputStreamReader(System.in)); String input; int num1, num2, divisor; // get user input System.out.println("Enter a number: "); input = kb.readLine(); num1 = Integer.parseInt(input); System.out.println("Enter a number: "); input = kb.readLine(); num2 = Integer.parseInt(input); // determine GCD while(num2 != 0){ divisor = num2; num2 = num1 % num2; num1 = divisor; } // print GCD System.out.println("GCD is " + num1); } } Hope this helps!

JohnnySo... at Yahoo! Answers Visit the source

Was this solution helpful to you?

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.