Calculate Nth root with integer arithmetic

前端 未结 6 923
梦如初夏
梦如初夏 2020-12-16 15:12

There are a couple of ways to find integer square roots using only integer arithmetic. For example this one. It makes for interesting reading and also a very interesting the

6条回答
  •  庸人自扰
    2020-12-16 15:40

    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.

提交回复
热议问题