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

217 visualizaciones (últimos 30 días)
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.

Respuestas (1)

John D'Errico
John D'Errico el 16 de Feb. de 2020
Editada: John D'Errico el 16 de Feb. de 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 comentarios
Will Murphy
Will Murphy el 17 de Feb. de 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 el 19 de Feb. de 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

Iniciar sesión para comentar.

Categorías

Más información sobre Programming en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by