0

I am working on a Java program to find s and t values for a GCD and for some reason my program won't get out of the user input unless I type in the integers 2 and 3 as the input. I don't know why it is doing that, and why it is only accepting those two numbers. If anyone could help me out, I would be very thankful.

Here is my code:

package test;
import java.util.Scanner;
public class test {
public static void main(String [] args) {

    int a;
    int b;
    int div;
    int dive;
    Scanner sc= new Scanner(System.in);
    System.out.println("Enter in values of A and B to find its GCD.");
    a = sc.nextInt();
    b = sc.nextInt();

    int[] Array1 = {1,0,a};
    int[] Array2 = {0,1,b};

    while (Array2[2] !=0) {
        if(Array1[2] > Array2[2])
        {
         div = Array1[2]/Array2[2];
        for (int i = 0; i<Array1.length;i++)
            for (int k = 0; k<Array2.length;k++)
                Array1[i] = Array1[i] - div* Array2[k];


        }
        else
        {
            dive = Array2[2]/Array1[2];
            for (int j = 0; j<Array1.length;j++)
                for (int l = 0; l<Array2.length;l++)
                    Array2[l] = Array2[l]- dive*Array1[j];
        }
      }
    if(Array2[2] == 0)
        System.out.println("S = " + Array1[0] + " t = " + Array1[1]);
    if(Array1[2] == 0)
        System.out.println("S = " + Array2[0] + " t = " + Array2[1]);


}
}

2 Answers 2

1

The problem is not in your scanner,the problem is your while loop and for loops. Let a=2,b=4 : ( b is Array2[2])

else
    {
        dive = Array2[2]/Array1[2];
        for (int j = 0; j<Array1.length;j++)
            for (int l = 0; l<Array2.length;l++)
                Array2[l] = Array2[l]- dive*Array1[j];
    }

dive=2

j=0 , l=2 --> b = b - 2*1 --> b=2

j=1 , l=2 --> b = b - 2*0 --> b=2

j=2 , l=2 --> b = b - 2*2 --> b=-2

As you can see, your value is not coming to zero,so this makes to loop forever.

Sign up to request clarification or add additional context in comments.

Comments

0

Your code is running into infinite loop that is because your while condition Array2[2] != 0 is never met.

You can see that by printing Array2[2]'s value to the end of your for loops.

You have to make a different approach.

Hint: Use Euclidean algorithm to calculate GCD.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.