The quotient and remainder of a number divided by another (Euclidean Division)

202 Ansichten (letzte 30 Tage)
Hi, I'm trying to write a code that takes (n,d)∈ ZxN & returns (q,r)∈ Z^2 such that n = qd + r with 0<=r<d.
How do I go about this? I've tried this many ways but my biggest issue is getting the quotient to equal the correct value so 0<=r<d.
An example is for n = 19 & d = 3, what ways can I edit this to do my task.
n = 19
d = 3
r = rem(n,d)
q = (n-r)/d
disp(q,r)
I understand this is very basic coding however I only started coding on friday so any help would be appreciated.

Antworten (1)

John D'Errico
John D'Errico am 16 Feb. 2020
Bearbeitet: John D'Errico am 16 Feb. 2020
What is the problem? :) You did it correctly. Well, except for the very last line.
n = 19
d = 3
r = rem(n,d)
q = (n-r)/d
disp(q,r)
n =
19
d =
3
r =
1
q =
6
As you should know, 19 can be written as 6*3 + 1. So we found r=1, and q = 6. Perfect. WTP?
disp(q,r)
Error using disp
Too many input arguments.
Your problem was in the use of disp. You might do it like this instead:
disp([q,r])
6 1
Oh, you will also find that using a semi-colon at the end of your lines is a good idea as you go further. Otherwise, MATLAB will dump reams and reams of junk on the commandline.
Finally, be careful using rem, since rem and mod have subtly different behaviors for negative arguments. So I would note that:
rem(-19,3)
ans =
-1
returns a remainder that does not live in the interval [0,d-1].
  2 Kommentare
Will Murphy
Will Murphy am 17 Feb. 2020
Okay, thank you for the clarificaton. In your last points case what should I do to find a remainder for a negative number.
John D'Errico
John D'Errico am 19 Feb. 2020
help mod
Mod always returns a remainder that lies in the interval you wish it to lie in, thus a POSITIVE remainder.
r = mod(-19,3)
r =
2
(-19 - r)/3
ans =
-7
Where we have the result: -19 = -7*3 + 2

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Programming finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by