Question 17
Given the following function:
Which value of x will cause foo(x) to print nothing (i.e., empty output)?
Hint
A simple solution would be to try out each of the options given to see if one or more of them work. However, with some observation, you might be able to deduce the logic of this function's if-else structure.
Solution
Observe that each if condition branch will result in something printed out.
x > 100:'Too much!'x % 10:'OK'x % 3:'KO'
We know we need an input x which will not print out anything, hence our x should not satisfy any of the above conditions, i.e., should:
- be \(\leq 100\) (to not satisfy
x > 100) - be a multiple of 10, or give remainder 0 when divided by 10 (to not satisfy
x % 10) - be a multiple of 3, or give remainder 0 when divided by 3 (to not satisfy
x % 3)
The last two conditions can be a bit tricky to wrap you head around, as instead of an outright Boolean value like what x > 100 will produce, both x % 10 and x % 3 will produce numerical values.
Right here, we need to find how to make these two expressions result in a falsy value, that is in our case, 0.
The modulo operator % is a remainder operator, which produces the remainder result from a division between two numbers - for instance,
11 % 5 = 1since \(11\div 5 = 2\text{ remainder } 1\), and15 % 5 = 0since \(15\div 5 = 3\text{ remainder }0\).
The correct answer is a number less than 100 which is a multiple of both 3 and 10. For the math-savvy, \(x = \{x: x \leq 100, 3 \mid x, 10 \mid x\}\) (correct me if the math notation is wrong). Hence, either 30, 60, or 90 will work.