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

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

提交回复
热议问题