Javascript code about math factorials

I am reading this book in JavaScript which has an exercise on calculating mathematical factorials. Well, it is presented in a playful way in which the code has to print out a word (in this case "clunk") and the time it takes to print it depends on the number that is passed as an argument to the function call.

In this example, the number is 5, so you can make a total of 120 combinations (5x4x3x2x1).

The point is that I find it difficult to understand the logic of the code. Here he is:

function clunk(times) {
    var num = times;
    while (num > 0) {
        display("clunk");
        num = num - 1;
    }
}

function thingamajig(size) {
    var facky = 1;
    clunkCounter = 0;

    if (size === 0) {
        display("clank");

    } else if (size === 1) {
        display("thunk");

    } else {
        while (size > 1) {
            facky = facky * size;
            size = size - 1;
        }
        clunk(facky);
    }
}

function display(output) {
    console.log(output);
    clunkCounter = clunkCounter + 1;
}

var clunkCounter = 0;
thingamajig(5);
console.log(clunkCounter);

      

My understanding after reading the code was that the word "clunk", is printed 5 times, then 4, then 3, 2 and 1, for a total of 15 times because I thought every pass through the loop was added, not multiplied ... I don't see in the code why the first loop should be multiplied by the second loop and so on until it reaches 1?

+3


source to share


2 answers


However, the code will print clunk

120 times. The function clunk()

will print a word clunk

multiple times equal to its first parameter. The sentence else

thingamajig

calculates the factorial of your supplied number like this:

while (size > 1) {
    facky = facky * size;
    size = size - 1;
}

      

Expanded using your input 5, which will execute as:

facky = 1;
size = 5;

facky = facky * 5;  // Now facky = 5
size = 5 - 1;       // Now size = 4

facky = facky * 4;  // Now facky = 20
size = 4 - 1;       // Now size = 3

facky = facky * 3;  // Now facky = 60
size = 3 - 1;       // Now size = 2

facky = facky * 2;  // Now facky = 120
size = 2 - 1;       // Now size = 1, we stop our while loop

      



Then it calls clunk(facky)

that matters 120

, giving us the current output.


If it was supposed to print 15 times - using the logic you provided - instead the thingamajig

sentence thingamajig

looks like this:

} else {
    while (size >= 1) {
        clunk(size);
        size = size - 1;
    }
}

      

+5


source


I would suggest running the code, preferably with a debugger. You will see "clunk" displayed 120 times. Note that the function clunk

is called only once, it is outside the loop.



So the loop calculates facky

(1 * 5 * 4 * 3 * 2 = 120) and then the loop exits. Calling the function clunk

once with parameter 120.

+1


source







All Articles