Logic to check the number is divisible by 3 or not?

后端 未结 10 1505
清歌不尽
清歌不尽 2021-01-14 16:31

without using %, / or * , I have to find the no. is divisible by 3 or not?

it might be an interview question.

Thanks.

10条回答
  •  清歌不尽
    2021-01-14 17:03

    There are various ways. The simplest is pretty obvious:

    int isdivby3(int n) {
        if (n < 0) n = -n;
    
        while (n > 0) n -= 3;
    
        return n == 0;
    }
    

    But we can improve that. Any number can be represented like this: ("," means range inclusive):

    Base2 (AKA binary)
    (0,1) + 2*(0,1) + 4*(0,1)
    
    Base4
    (0,3) + 4*(0,3) + 16*(0,3)
    
    BaseN
    (0,N-1) + N*(0,N-1) + N*N*(0,N-1)
    

    Now the trick is, a number x is divisible by n-1 if and only if the digitsum of x in base n is divisible by n-1. This trick is well-known for 9:

    1926 = 6 + 2*10 + 9*100 + 1*1000
    6+2+9+1 = 8 + 1*10
    8+1 = 9 thus 1926 is divisible by 9
    

    Now we can apply that for 3 too in base4. And were lucky since 4 is a power of 2 we can do binary bitwise operations. I use the notation number(base).

    27(10) = 123(4)
    Digitsum
    12(4)
    Digitsum again
    3(4) = Divisible!
    

    Now let's translate that to C:

    int div3(int n) {
        if (n < 0) n = -n;
        else if (n == 0) return 1;
    
        while (n > 3) {
            int d = 0;
    
            while (n > 0) {
                d += n & 3;
                n >>= 2;
            }
    
            n = d;
        }
    
        return n == 3;
    }
    

    Blazing fast.

提交回复
热议问题