1
/*************************************************
2
* Division Algorithm Source File *
3
* (C) 1999-2007 The Botan Project *
4
*************************************************/
6
#include <botan/numthry.h>
7
#include <botan/mp_core.h>
13
/*************************************************
14
* Handle signed operands, if necessary *
15
*************************************************/
16
void sign_fixup(const BigInt& x, const BigInt& y, BigInt& q, BigInt& r)
18
if(x.sign() == BigInt::Negative)
21
if(r.is_nonzero()) { --q; r = y.abs() - r; }
23
if(y.sign() == BigInt::Negative)
29
/*************************************************
30
* Solve x = q * y + r *
31
*************************************************/
32
void divide(const BigInt& x, const BigInt& y_arg, BigInt& q, BigInt& r)
35
throw BigInt::DivideByZero();
38
const u32bit y_words = y.sig_words();
41
r.set_sign(BigInt::Positive);
42
y.set_sign(BigInt::Positive);
44
s32bit compare = r.cmp(y);
56
word y_top = y[y.sig_words()-1];
57
while(y_top < MP_WORD_TOP_BIT) { y_top <<= 1; ++shifts; }
61
const u32bit n = r.sig_words() - 1, t = y_words - 1;
63
q.get_reg().create(n - t + 1);
66
while(r > y) { r -= y; q++; }
68
sign_fixup(x, y_arg, q, r);
72
BigInt temp = y << (MP_WORD_BITS * (n-t));
74
while(r >= temp) { r -= temp; ++q[n-t]; }
76
for(u32bit j = n; j != t; --j)
78
const word x_j0 = r.word_at(j);
79
const word x_j1 = r.word_at(j-1);
80
const word y_t = y.word_at(t);
83
q[j-t-1] = MP_WORD_MAX;
85
q[j-t-1] = bigint_divop(x_j0, x_j1, y_t);
87
while(bigint_divcore(q[j-t-1], y_t, y.word_at(t-1),
88
x_j0, x_j1, r.word_at(j-2)))
91
r -= (q[j-t-1] * y) << (MP_WORD_BITS * (j-t-1));
94
r += y << (MP_WORD_BITS * (j-t-1));
101
sign_fixup(x, y_arg, q, r);