Search code examples
cmathematical-expressions

How to make a logical selection using calculations in c?


I am helping my daughter with an intro to c programming assignment, and her homework contains a simple menu like this:

Please choose an option below:
------------------------------
1. Linear time
2. Logarithmic time
3. Exponential time

Now, usually it would be quite simple to determine what the menu choice is, but she is not allowed to use logical operators, relational operators, bitwise operators, or selection constructs. We have been trying to use modulus, but to no avail. Is this even possible? She can essentially only use +, -, *, /, and %. As well as simple variables.

The only solution we have come up with so far is using equality:

(choice==1)*n + (choice==2)*log(n) + (choice==3)*(n*n)

where n is the size of the data set to sort, but that is not allowed.


Solution

  • only use +, -, *, /, and %

    Hmm - strange restriction


    Instead of (choice==1)*foo1 + (choice==2)*foo2 + (choice==2)*foo3

    Use multiplication, division to effect the == for select values of choice 1,2,3.

    (choice-2)*(choice-3)/((1-2)*(1-3)) * foo1 + 
    (choice-1)*(choice-3)/((2-1)*(2-3)) * foo2 + 
    (choice-1)*(choice-2)/((3-1)*(3-2)) * foo3
    

    Notice (choice-2)*(choice-3)/((1-2)*(1-3)) is 1 when choice==1 otherwise 0.


    This technique is like The Lagrange method in polynomial curve fitting.