Skip to content

Commit 6a95b88

Browse files
committedJan 16, 2018
fix bigint remainder division
See #405
1 parent 84d8584 commit 6a95b88

File tree

2 files changed

+17
-8
lines changed

2 files changed

+17
-8
lines changed
 

‎src/bigint.cpp

+16-8
Original file line numberDiff line numberDiff line change
@@ -1015,21 +1015,29 @@ static void bigint_unsigned_division(const BigInt *op1, const BigInt *op2, BigIn
10151015

10161016
// If the caller wants the quotient
10171017
if (Quotient) {
1018-
Quotient->digit_count = lhsWords;
1019-
Quotient->data.digits = allocate<uint64_t>(lhsWords);
10201018
Quotient->is_negative = false;
1021-
for (size_t i = 0; i < lhsWords; i += 1) {
1022-
Quotient->data.digits[i] = Make_64(Q[i*2+1], Q[i*2]);
1019+
Quotient->digit_count = lhsWords;
1020+
if (lhsWords == 1) {
1021+
Quotient->data.digit = Make_64(Q[1], Q[0]);
1022+
} else {
1023+
Quotient->data.digits = allocate<uint64_t>(lhsWords);
1024+
for (size_t i = 0; i < lhsWords; i += 1) {
1025+
Quotient->data.digits[i] = Make_64(Q[i*2+1], Q[i*2]);
1026+
}
10231027
}
10241028
}
10251029

10261030
// If the caller wants the remainder
10271031
if (Remainder) {
1028-
Remainder->digit_count = rhsWords;
1029-
Remainder->data.digits = allocate<uint64_t>(rhsWords);
10301032
Remainder->is_negative = false;
1031-
for (size_t i = 0; i < rhsWords; i += 1) {
1032-
Remainder->data.digits[i] = Make_64(R[i*2+1], R[i*2]);
1033+
Remainder->digit_count = rhsWords;
1034+
if (rhsWords == 1) {
1035+
Remainder->data.digit = Make_64(R[1], R[0]);
1036+
} else {
1037+
Remainder->data.digits = allocate<uint64_t>(rhsWords);
1038+
for (size_t i = 0; i < rhsWords; i += 1) {
1039+
Remainder->data.digits[i] = Make_64(R[i*2+1], R[i*2]);
1040+
}
10331041
}
10341042
}
10351043
}

‎test/cases/math.zig

+1
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ fn testDivision() {
4747
assert(@divTrunc(-1194735857077236777412821811143690633098347576,
4848
-508740759824825164163191790951174292733114988) ==
4949
2);
50+
assert(4126227191251978491697987544882340798050766755606969681711 % 10 == 1);
5051
}
5152
}
5253
fn div(comptime T: type, a: T, b: T) -> T {

0 commit comments

Comments
 (0)
Please sign in to comment.