Skip to content

Commit 4d3b6b6

Browse files
committed
Fix bigint sub, use smaller precision for inv in divmod
1 parent 9c1de86 commit 4d3b6b6

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

cp-algo/math/bigint.hpp

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,10 +134,16 @@ namespace cp_algo::math {
134134
if (i < N) {
135135
d_ptr[i]--;
136136
} else {
137-
d_ptr[0]--;
137+
// Two's complement: flip all digits then add 1
138138
for (i = 0; i < N; i++) {
139139
d_ptr[i] = base - d_ptr[i] - 1;
140140
}
141+
bool carry = true;
142+
for (i = 0; i < N && carry; i++) {
143+
d_ptr[i]++;
144+
carry = d_ptr[i] >= base;
145+
d_ptr[i] -= carry * base;
146+
}
141147
negate();
142148
}
143149
}

cp-algo/math/decimal.hpp

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -155,12 +155,16 @@ namespace cp_algo::math {
155155
// General case using decimal arithmetic
156156
auto A = decimal<base>(a);
157157
auto B = decimal<base>(b);
158-
auto d = (A * B.inv(A.magnitude())).trunc();
158+
auto d = (A * B.inv(A.magnitude() - B.magnitude() + 1)).round();
159159
auto r = a - d * b;
160160
if (r >= b) {
161161
d += 1;
162162
r -= b;
163163
}
164+
if (r < bigint<base>(0)) {
165+
d -= 1;
166+
r += b;
167+
}
164168
return std::pair{d, r};
165169
}
166170
}

0 commit comments

Comments
 (0)