Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer division

Tags:

pseudocode

I have faced the following interview question.

Consider this function declaration:

void quiz(int i)
{
    if (i > 1)
    {
        quiz(i / 2);
        quiz(i / 2);
    }
    writeOutput("*");
}

How many asterisks are printed by the function call quiz(5)?

My answer was:

Languages (Javascript, PHP, etc.) with integer division result type is float - seven asterisks. Function quiz get called:

  1. With i=5 – once, asterisk printed.
  2. With i=2.5 – twice, asterisks printed.
  3. With i=1.25 – four times, asterisks printed.
  4. With i=0.625 – eight times, no asterisks printed

Languages (C/C++, C#, Java, etc.) which division result type name is integer - three asterisks. Function quiz get called:

  1. With i=5 – once, asterisk printed.
  2. With i=2 – twice, asterisks printed.
  3. With i=1 – four times, asterisks not printed.

Question syntax is like C/C++, Java, so the answer would be three

The interview was a closed book exam - during the interview I was unable to run this code and check it. The interviewer told me that my answer is not absolutely correct (or at least, they didn't expect it to be like this). Hovewer, I've ran this code (with PHP, Javascript and C#) at home and the result was as I described.

So, are there some caveats I'm missing or my answer was just more detailed than they were expecting?

like image 983
J0HN Avatar asked Jul 06 '26 00:07

J0HN


2 Answers

If you change the code to this:

void quiz(int i)
{
    if (i > 1)
    {
        quiz(i / 2);
        quiz(i / 2);
    }
    printf("* for %d\n", i);
}

You'll see that the result for quiz(5) is:

* for 1
* for 1
* for 2
* for 1
* for 1
* for 2
* for 5

So, you got the correct number of calls per i, you just didn't notice that the writeOutput is outside the if, not inside it.

like image 85
Douglas Avatar answered Jul 14 '26 02:07

Douglas


writeOutput is going to be called when i <= 1, too.

like image 37
Paul Williams Avatar answered Jul 14 '26 02:07

Paul Williams