Post Reply 
(42S) Quotient and Remainder
04-05-2023, 09:38 AM (This post was last modified: 04-06-2023 11:54 AM by Werner.)
Post: #1
(42S) Quotient and Remainder
[Updated to use floor-divide. X and/or Y may be negative, and Y = Q*X+R holds when possible]
The 41C version was easy, but here we have to solve the halfway problem, eg:
Y: 8e11+2
X: 4
must return
Q: 2E11
R: 2

but

Y: 8e11+6
X: 4
must return
Q: 2E11+1
R: 2

In the first case, the division rounds down, in the second it rounds up.

Thanks to Albert Chan for the halfway correcting algorithm.
(which I adapted so I could keep on using IP instead of FLOOR)

split Y = Q*X + R

t := X/Y;
Q := INT(t);
R := MOD(Y,X);
if t#Q then return(R,Q);
t := X - R;
if t<R then Q:= Q - 1;
if t=R then Q:= Q - MOD(FLOOR(MOD(Y,X*10)/X),2); /* equals IP(MOD(MOD(Y,X*10)/X,2)) */
return(R,Q);

Code:
@ given X and Y, determine Quotient DIV(Y,X) and Remainder MOD(Y,X)
@               L       X       Y       Z       T
@ In:                   X       Y
@ Out:          X       R       Q
00 { 69-Byte Prgm }
01▸LBL "RQ" @           X       Y
02 RCL ST Y
03 RCL÷ ST Y @         Y/X      X       Y
04 ENTER
05 IP @                 Q      Q..      X       Y
06 X=Y?
07 GTO 00
08 X>Y? @ FLOOR
09 DSE ST X @ always skips
10 X≠Y? @ NOP
11 R↓
12 R↓ @                 X       Y       Q
13 MOD @        X       R       Q
14 RTN
15▸LBL 00 @             Q       Q       X       Y
16 R^ @                 Y       Q       Q       X
17 STO ST Z
18 R^ @                 X       Y       Q       Y
19 MOD @        X       R       Q       Y       Y
20 LASTX
21 RCL- ST Y @  X      X-R      R       Q       Y
22 X=Y?
23 GTO 02
24 X<Y?
25 +/-
26 X<0?
27 DSE ST Z @ will skip when Q is negative
28▸LBL 00
29 R↓
30 RTN
31▸LBL 02 @             R       R       Q       Y
32 R↓
33 X<> ST Z @           Y       Q       R       R
34 20
35 RCL× ST T @         X.10     Y       Q       R
36 MOD
37 R^
38 STO+ ST X
39 ÷
40 2
41 MOD
42 IP
43 -
44 R↓
45 +
46 -
47 +/-
48 END

examples:

[code]Y: 4e11+39       Q: 1e10
X: 40            R: 39

Y: 2e12          Q: 666 666 666 666
X: 3             R: 2

Y: 5e23          Q: 5e11
X: 1e12-1        R: 5e11

Y: 2e23+3e12     Q: 5e11+7
X: 4e11          R: 2e11

will work for X and Y integers, abs(X)<1e12 and abs(Y)<=X*1e12
I confess I haven't tried it with fractional inputs, but that should also work. Counterexamples welcome, I think ;-)
As with the 41 code, this routine will work when Q can be represented with 12 digits eg Y=1e40 and X=6 will not work.

Cheers, Werner

41CV†,42S,48GX,49G,DM42,DM41X,17BII,15CE,DM15L,12C,16CE
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
(42S) Quotient and Remainder - Werner - 04-05-2023 09:38 AM
RE: (42S) Quotient and Remainder - Werner - 04-05-2023, 01:11 PM
RE: (42S) Quotient and Remainder - Werner - 04-05-2023, 03:55 PM



User(s) browsing this thread: 1 Guest(s)