Consider, we are only allowed to use loops ($while$), addition ($+$), substraction ($-$) and checking if a value is $> 0$. How can one find out, if a certain variable $x$ equals a value $y$? E.g. how can I find out if $x=4$ by only using the aforementioned methods? For $x=0$ I came up with the following:

y = 1
while x > 0:
    y = y - 1
    x = x - 1
while y > 0:
   do something

This way, $something$ gets only executed if $x=0$. But I have no clue about values above $0$.


Start by calculating $x-y$. This is simple enough:

while y > 0:
    y -= 1
    x += 1

Now, compare what you got with $0$. That is, compare the value of $x$ after the loop to $0$, using the technique you thought of. This will guarantee that "$something$" is executed only if $x-y=0$, or equivalently if $x=y$.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.