Euclidean algorithm explanation?

73 Views Asked by At

Two inputs, number1 = 36 and number2 = 27, are passed to the following code for finding G.C.D of two numbers using Euclidean algorithm.

public static int euclideanAlgo(int number1, int number2){
    int temp;
    while(number2 != 0){
        temp = number2;
        number2 = number1 % number2;
        number1 = temp;
    }
    return number1;
}

During the first iteration, in line number1 = temp :

Is the value of number1 = 27? or is it the updated value 9,since temp = number2 and in the next line number2 = number1 % number2 which becomes 9?

3

There are 3 best solutions below

0
On BEST ANSWER

You are implying that since number2 is updated, the previous assignment of temp would then change.

This is not the case with Java, although this technique is used widely in many other coding languages, such as C.
In fact, Java was designed specifically with an aim to avoid this programming concept.

It is referred to as referencing, and dereferencing.  Here is a great Wikipedia article on the technique.
Wikipedia – Reference_(computer science).

It was very useful in early coding languages, as CPU time was critical.
As computers advanced the concept was lost, and deemed unnecessary.

I believe in intense processing applications, this technique is still preferred.

0
On

You we follow execution of the algorithm we have :

number1 = 36
number2 = 27

number2 == 0? // No number2 = 27
    temp = number2 // temp=27
    number2 = number1%number2 // number2 = 36%27 = 9
    number1 = temp // number1=27

number2 == 0? // No number2 = 9
    temp = number2 // temp = 9
    number2 = number1%number2 // number2 = 27%9 = 0
    number1 = temp // number1 = 9

return number1 // number1 = 9

0
On

It helps to think of number1, number2, and temp as three separate boxes, each containing a number. An assignment a = b is in fact a ← b, that is, it copies the value from box b into box a. It does not create any links between boxes.

Here are the values in boxes after each line:

...                            number1  number2  temp
...                               36       27     ??
temp = number2;                   36       27     27
number2 = number1 % number2;      36        9     27
number1 = temp;                   27        9     27