@@ -117,24 +117,20 @@ extension BinaryInteger {
117117 if q. _lowWord & 1 == 1 { return q }
118118
119119 case . stochastically:
120- var qhi : UInt64
120+ let bmag = other. magnitude
121+ let rmag = r. magnitude
122+ var bhi : UInt64
121123 var rhi : UInt64
122124 if other. magnitude <= UInt64 . max {
123- qhi = UInt64 ( other . magnitude )
124- rhi = UInt64 ( r . magnitude )
125+ bhi = UInt64 ( bmag )
126+ rhi = UInt64 ( rmag )
125127 } else {
126- // TODO: this is untested currently.
127- let qmag = other. magnitude
128- let shift = qmag. _msb - 1
129- qhi = UInt64 ( truncatingIfNeeded: qmag >> shift)
130- rhi = UInt64 ( truncatingIfNeeded: r. magnitude >> shift)
128+ let shift = bmag. _msb - 63
129+ bhi = UInt64 ( truncatingIfNeeded: bmag >> shift)
130+ rhi = UInt64 ( truncatingIfNeeded: rmag >> shift)
131131 }
132- let ( sum, car) = rhi. addingReportingOverflow ( . random( in: 0 ..< qhi) )
133- if car || sum >= qhi {
134- if ( other > 0 ) != ( r > 0 ) { return q- 1 }
135- return q+ 1
136- }
137- return q
132+ let ( sum, car) = rhi. addingReportingOverflow ( . random( in: 0 ..< bhi) )
133+ if sum < bhi && !car { return q }
138134
139135 case . requireExact:
140136 preconditionFailure ( " Division was not exact. " )
@@ -304,24 +300,20 @@ extension SignedInteger {
304300 if q. _lowWord & 1 == 1 { return ( q, r) }
305301
306302 case . stochastically:
307- var qhi : UInt64
303+ let bmag = other. magnitude
304+ let rmag = r. magnitude
305+ var bhi : UInt64
308306 var rhi : UInt64
309307 if other. magnitude <= UInt64 . max {
310- qhi = UInt64 ( other . magnitude )
311- rhi = UInt64 ( r . magnitude )
308+ bhi = UInt64 ( bmag )
309+ rhi = UInt64 ( rmag )
312310 } else {
313- // TODO: this is untested currently.
314- let qmag = other. magnitude
315- let shift = qmag. _msb - 1
316- qhi = UInt64 ( truncatingIfNeeded: qmag >> shift)
317- rhi = UInt64 ( truncatingIfNeeded: r. magnitude >> shift)
311+ let shift = bmag. _msb - 63
312+ bhi = UInt64 ( truncatingIfNeeded: bmag >> shift)
313+ rhi = UInt64 ( truncatingIfNeeded: rmag >> shift)
318314 }
319- let ( sum, car) = rhi. addingReportingOverflow ( . random( in: 0 ..< qhi) )
320- if car || sum >= qhi {
321- if ( other > 0 ) != ( r > 0 ) { return ( q- 1 , r+ other) }
322- return ( q+ 1 , r- other)
323- }
324- return ( q, r)
315+ let ( sum, car) = rhi. addingReportingOverflow ( . random( in: 0 ..< bhi) )
316+ if sum < bhi && !car { return ( q, r) }
325317
326318 case . requireExact:
327319 preconditionFailure ( " Division was not exact. " )
0 commit comments