How Does This Division Algorithm Work with Repeated Subtraction?

0
9
Asked By CuriousCat123 On

Hey everyone! I just started learning programming a few days ago, and I have a question about a division algorithm that uses repeated subtraction. I'm trying to understand how it would work with inputs like -4 divided by 3 and 4 divided by 3. I'm really struggling with the pseudocode below and how the different functions work together, especially when handling negative numbers. Can someone help me walk through how it plays out with these inputs? I'm curious about how the functions are called and what results I should expect! Thanks a lot!

function divide(N, D)

if D = 0 then error(DivisionByZero) end

if D < 0 then (Q, R) := divide(N, -D); return (-Q, R) end

if N = D do
Q := Q + 1
R := R - D
end

return (Q, R)
end

1 Answer

Answered By HelpfulCoder99 On

It looks like you're digging deep into the pseudocode! The function starts by flipping the signs of the inputs until both are positive, allowing it to use the `divide_unsigned` function. The confusion often comes from how recursive calls work. Basically, the `divide` function calls itself with adjusted values until it reaches a state where it can handle non-negative inputs in `divide_unsigned`. So, if you input -4 and 3, it would eventually calculate and return the result, which involves flipping the sign back as needed. Hang in there, and don't get too wrapped up in pseudocode; writing actual code will help more!

LearningLoop -

So if it flips the sign like that, does it mean if we input -4/3 it will give a quotient of 1? Also, how does it "fall through" to the next function? I’m not clear on how it calls itself while returning Q and R rather than just N and D. Doesn't it need to return to the original inputs to call itself again?

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.