Why does it work?
Pretty easy really. I’ll try to explain in English rather than math-ese; I’m sure a prof will come along to clarify the notation. And from here on out we’re going to be talking strictly about integers, so I won’t mention that caveat again.
To say a number is divisible by 3 is really to say the remainder is zero when you divide it by 3.
Consider a 2-digit number whose digits are X & Y (i.e. written “XY”). The value is 10X+Y.
Whatever actual value it has, the remainder when divided by 3 is 0, 1, or 2.
Compare the value 10X + Y (the true value) with the value X+Y (the sum-of-digits value). i.e subtract X+Y from 10X+Y.
What’s the resulting difference? 9X. Is 9X disivible by 3? Yes, always, regardless of the value of X, becasue the 9 is divisible by 3. Or in other words, the remainder of 9X divided by 3 is zero for all values of X.
So you can remove 9X-worth of the value from the 10X+Y and still have the same divide-by-3 remainder. If the remainder was 0 before, it’s still 0 now. Or, if 10X+Y was divisible by 3, so is X+Y. Or in specifics, if 42 is divisible by 3, so is 4+2.
QED, at least for 2-digit numbers.
The same logic can be applied to 3 digit numbers too, and by induction to numbers of any length. If the sum is itself multi-digited, just add those digits together, and keep repeating the sum-of-digits process until you get to a single digit result. e.g. 3456789 -> 42 -> 6 is divisible by 3.
A similar method also works for determining if something is divisible by 9. Take a look at 9, 18, 27, 36, 45, 54, 63, 72, 81, 90, 99, 108, etc. In each case add the digits (multiple times if necessary) and if they sum to 9, your original number is divisible by 9.
In number bases other than the traditional base ten we use, this same method still works, but for different values. It always works for the number one less than the base value. For example, in base eight, it works for seven. In base sixteen it works for fifteen.
And it’ll always work for the values which factor that (base minus one) value. In traditional base ten, nine is disivible by three and so it also works for three. In base eight, seven is prime and so it only works for seven. In base sixteen, fifteen is divisible by five and three, and so it works for five and three.
Integer math is fun that way.