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

后端 未结 10 1407
清歌不尽
清歌不尽 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 16:46

    A number is divisible by three if its binary alternating digit sum is zero:

    bool by3(int n) {
      int s=0;
      for (int q=1; n; s+=q*(n&1), n>>=1, q*=-1);
      return !s;
    }
    
    0 讨论(0)
  • 2021-01-14 16:46

    You could use user feedback:

    int isDivisibleBy3(int n)
    {
       int areDivisibleBy3[] = {};
       for(int i = 0; i < 0; i++)
       {
           if(n == areDivisibleBy3[i])
           {
               return 1;
           }
       }
    
       return 0;
    }
    

    When a user reports a bug stating that a number that is divisble by 3 is not giving the correct result, you simply add that number to the array and increase the number i is compared to in the for loop condition.

    This is great because then you never have to worry about numbers the user never uses.

    Don't forget to add a unit test for whenever a user reports a bug!

    0 讨论(0)
  • 2021-01-14 16:47

    Here is a reasonably efficient algorithm for large numbers. (Well not very efficient, but reasonable given the constraints.)

    Use sprintf to convert it to a string, convert each digit back to a number. Add up the digits. If you come up with 3, 6, or 9, it is divisible by 3. Anything else less than 10, it is not. Anything over 9, recurse.

    For instance to test the number 813478902 you'd stringify, then add the digits to get 42, add those digits to get 6, so it is divisible by 3.

    0 讨论(0)
  • 2021-01-14 16:47

    just use a for loop subtracting 3 over and over and see if you get to 0. if you get to negative without getting to 0 then you know its not divisible by 3

    0 讨论(0)
  • 2021-01-14 16:52

    The simplest way to know if a number is divisible by 3 is to sum all its digits and divide the result by 3. If the sum of the digits is divisible by 3, so the number itself is divisible by 3. For instance, 54467565687 is divisible by 3, because 5+4+4+6+7+5+6+5+6+8+7 = 63, and 63 is divisible by 3. So, no matter how big is the number, you can find if it is divisible by 3 just adding all its digits, and subtracting 3 from the value of this sum until you have a result smaller than 3. If this result is 0, the value of the sum is divisible by 3 (and so the original number), otherwise the sum is not divisible by 3 (and the original number is not divisible, either). It's done much more quickly than subtract 3 successively from the original number (of course, specially if it is a large number) and with no divisions. Um abraço a todos.

    Artur

    0 讨论(0)
  • 2021-01-14 16:54
    number = abs(number)
    
    while (number > 0)
    {
       number -= 3;
    }
    
    return number == 0
    
    0 讨论(0)
提交回复
热议问题