In C, you can write:
K = (M == N);where K, M and N are integers. Then K = 0 (false) if M is not equal to N, and K = -1 (true) if M is equal to N. What makes this work is that the boolean expression actually returns a numerical value.
In Fortran, there is a LOGICAL data type. A LOGICAL variable is meant to have only the values TRUE or FALSE, but since it's typically stored in a full integer word, it's possible, at least in some implementations, to convert a logical value to an integer. Thus, you might be able to use a statement like the following:
K = int ( M == N )where ( M == N ) is a logical function that returns TRUE if M and N are equal integers. The int function then converts this TRUE or FALSE value to an integer, presumably 1 or 0.
Let's assume, however, that we cannot use logical operators or logical variables, but only the various arithmetic operations and variables available to us.
So here is the quiz. Can you write an arithmetic expression in a single line of Fortran in the form
K = f ( M, N );which accepts any pair of integers M and N, and returns the value 1 if they are equal, and 0 otherwise. To be clear about what is being asked, the desired value of K is the same as what would be computed by the following lines:
if ( M == N ) then K = 1 else K = 0 end if
Suggestion: It would be enough if you can come up with a function F(I) which is 0 at 0, and 1 for all other integers, or vice versa.
Hats off to Jim Fink of Gettysburg College for posing this problem.
I give up, show me the solution.
Back to the puzzle page.