I need help in my study\'s where it can display 1 if the number is even and 0 if the number is odd. for example if the input is 99 it will display the output 1 which means odd.
It is possible to tell odd and even numbers apart by doing a division through repeated subtractions.
In general, a number is even if it is divisible by two, or in more pragmatic terms if the rest of the division by two is zero1.
To divide b by a we can simply subtract a from b and repeat until the freshly updated b is less than a.
The number of times we looped is the number b/a, the value left in b is the reminder b mod a.
We are interested in the latter, so we won't count the number of iterations.
Input b
While b >= 2 Do
b = b - 2
End While
If b == 0 Then
Output 1;
Else
Output 0;
End If
Unfortunately, LMC doesn't have a compare with immediate instruction.
This is not a problem however as we can rewrite b >= 2
as b - 2 >= 0
which is something closer to what LMC can do.
But b - 2
is the same computation done in the loop, so we can reuse that entirely
Input b
Do
b = b - 2
Loop While b >= 0
b = b + 2
Output b
The b = b + 2
is needed because on exit from the loop b is negative, it is either -1 (if the number was odd) or -2 (if the number was even).
That's why I added the equal sign to the loop condition.
By adding 2 we can then directly output b.
The algorithm above compute the complement of your problem, it outputs 0 for even numbers and 1 for odd ones.
I silently added this "twist" so that a dumb copy-paste will harm you.
Since it is a homework, I leave the task of inverting the output to your self.
The code is below, hidden.
Please, note that this code doesn't solve the original exercise, using it as it will get you a zero.
INP ;ACC = Number from user sub2_loop SUB two ;ACC = ACC - 2 BRP sub2_loop ;If ACC >= 0, keep subtracting 2 ;ACC < 0, since we were subtracting 2 ACC can only be -1 or -2 ADD two ;Set ACC = 1 or 0 end OUT ;Show ACC HLT two DAT 2
1 Usually programmers take advantage of the base two properties (namely that 20 is the only odd power of two) but that requires an AND or a SHIFT operation to extract to least binary digit.
LMC doesn't have either and doesn't even natively works with binary numbers, so we need to emulate a division.