Search code examples
c++algorithmnumbersmodulonumber-theory

Can I calculate modulus of large number by taking modulus of each digit and taking sum?


The problem is, I got all digits of a very large number, I need to find whether it is divisible by 3. I tried my approach which I suppose is wrong but I don't know why

This is my approach for example problem is (159%3)

I could write it as (100+50+9)%3 the above statement can be written as (1%3+5%3+9%3)%3 by (a+b)%c=(a%c+b%c)%c.

What is wrong in this approach?


Solution

  • To check for divisibility by 3, you only need to check if a number's digits sum to a number that is divisible by 3. For example, 159 is divisible by 3 because 1+5+9 = 15, which is divisible by three.

    Note that this approach only works for 3 and 9, so don't try using this for other modulos!