javaalgorithmeuclidean-algorithm

Euclidean algorithm explanation?


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?


Solution

  • 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.