The quotient and remainder of a number divided by another (Euclidean Division)
조회 수: 216 (최근 30일)
이전 댓글 표시
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.
댓글 수: 0
답변 (1개)
John D'Errico
2020년 2월 16일
편집: John D'Errico
2020년 2월 16일
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
John D'Errico
2020년 2월 19일
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
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!