You can use Newton's method using only integer arithmetic, the step is the same as for floating point arithmetic, except you have to replace floating point operators with the corresponding integer operators in languages which have different operators for these.
Let's say you want to find the integer-k-th root of a > 0
, which should be the largest integer r
such that r^k <= a
. You start with any positive integer (of course a good starting point helps).
int_type step(int_type k, int_type a, int_type x) {
return ((k-1)*x + a/x^(k-1))/k;
}
int_type root(int_type k, int_type a) {
int_type x = 1, y = step(k,a,x);
do {
x = y;
y = step(k,a,x);
}while(y < x);
return x;
}
Except for the very first step, you have x == r <==> step(k,a,x) >= x
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…