Long Division
Mostra commenti meno recenti
Hi im trying to write a function, that is basically long division, so i will get a value and then also a remainder. Could anybody give me some starting advice please?
function [q,r]=Divide(x,y)
Thats what my first line of my function shall be, where q is the integer value and r the remainder.
Thanks!
Risposte (2)
Walter Roberson
il 7 Mar 2012
0 voti
When you do division by hand, on a piece of paper, what you see is a vector of digits in the numerator and a vector of digits in the denominator. Humans do not usually perceive a number such as 2893 as a single unit: we see it as "two eight nine three". "long division" deals with the situation.
So, if someone gave you pencil and paper and two vectors of digits (numerator and denominator), and asked you to do the division, how would you proceed?
9 Commenti
Ben Davis
il 7 Mar 2012
Walter Roberson
il 7 Mar 2012
More or less. I probably would not describe it that way myself, but I get the impression you know what you mean.
Ben Davis
il 7 Mar 2012
Ben Davis
il 7 Mar 2012
Walter Roberson
il 7 Mar 2012
Long division:
First order of business is to check if the denominator vector is all zero; if it is, then exit with an appropriate error result.
Second order of business is to remove all leading 0's from the numerator and denominator vectors.
Third, initialize your result to 0
Loop
Is the numerator vector 0 ? If so then you are finished with a 0 remainder.
Is the denominator vector longer than the numerator vector? If so then you are finished and the numerator vector is your remainder.
Compare the denominator vector to the leading digits of the numerator vector. Is the denominator greater than those leading digits? If it is then the result-digit for that position is 0, and add an extra 0 to the end of the numerator vector to achieve the effect of multiplying by 10, and return to the beginning of the loop.
If the denominator was not greater than those leading digits then.... <etc>
end the loop
return the result and the remainder
Now, does _that_ look like your main problem is how you initialize x ??
Ben Davis
il 7 Mar 2012
Ben Davis
il 7 Mar 2012
Walter Roberson
il 7 Mar 2012
If you post what you have so far, someone might point out problems.
Ben Davis
il 8 Mar 2012
Modificato: Walter Roberson
il 10 Set 2019
Daniel Shub
il 7 Mar 2012
0 voti
In your first comment to Walter, you wrote "and the process is repeated until an answer is obtained." That sounds a lot like a "while" loop to me. Think you could express what you do in terms of a while loop ...
Maybe: While the remainder is less than the denominator DO ...
Then from there think about how to write the do in pseudo code. Finally convert it to MATLAB
Categorie
Scopri di più su Parallel Computing Toolbox in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!