Reputation: 33
I am trying to write a program in the MARIE assembly language that will divide two numbers using repeated subtraction. I need to count the number of subtractions needed before reaching zero or minus numbers.
My code:
Input
Store A
Input
Store B
Load A
Skipcond 800
Jump Endloop
Loop, Subt B
Store A
Load X
Add One
Store X
Load A
Skipcond 400
Jump Loop
Load X
Endloop, Halt
A, DEC 0
B, DEC 0
X, DEC 0
One, DEC 1
I get an infinite loop - What is my mistake?
Upvotes: 3
Views: 6805
Reputation: 351384
The issue in your code was already explained: as you only check whether the remainder becomes 0, you'll miss cases where it never becomes 0 but becomes negative.
You make the check on the remainder at the wrong moment. This should be done before storing that remainder and before incrementing the quotient.
Your program produces no output. I suppose it would be interesting to print the quotient and the remainder.
I would use more descriptive names and replace A
, B
and C
with Dividend
, Divisor
and Quotient
.
To support resetting the program counter to the top of your program, you should clear the variables that are supposed to have specific values at the start. In this case, the quotient should be set to 0.
Here is a working program for dividing a positive number by a positive divisor:
Clear
Store Quotient / Reset quotient, so previous run does not have impact
Input
Store Dividend / Use descriptive names
SkipCond 000 / Dividend less then 0?
Jump GetNext / No: continue to get next input
Halt / Yes: abort
GetNext, Input
Store Divisor
SkipCond 800 / Divisor greater than 0?
Halt / No: abort
/ Yes: start the calculation
Loop, Load Dividend
Subt Divisor
Skipcond 000 / Dividend < Divisor?
Jump Continue / No: subtract and continue
/ Yes: we're done: output results
Load Quotient
Output / Output Quotient
Load Dividend
Output / ...and remainder
Halt
Continue, Store Dividend
Load Quotient
Add One
Store Quotient
Jump Loop
/ Variables
Dividend, DEC 0
Divisor, DEC 0
Quotient, DEC 0
/ Constants
One, DEC 1
You can assemble and run this code on MARIE.js.org.
Upvotes: 0
Reputation:
Using Skipcond 400
if the number is not divisible by the divider
there will be an endless loop as it will go negative not zero.
Care needs to be taken not to increment X when the remainder is not divisible by B. So a check is made for the remainder equalling zero, so X can be incremented when A is no longer positive.
Input
Store A
Input
Store B
Loop, Load A
Subt B
Store A
Skipcond 800
Jump Endloop / While X is positive it will continue
Load X
Add One
Store X
Jump Loop
IncrementX, Load X
Add One
Store X
Load A
Subt B
Store A
Endloop, Load A
Skipcond 000 /Skip if negative
Jump IncrementX
Load X
Output
Halt
A, DEC 0
B, DEC 0
X, DEC 0
One, DEC 1
Upvotes: 1