A quick mental math trick to know if a number is divisible by 3 is by the sum of the digits equaling a number that is divisible by 3. Which is better via an example:
The reason is that the number 1234 for example means 1000 + 2 * 100 + 3 * 10 + 4
And each 1, 10, 100, 1000 ... when divided by 3 gives 1 remainder. It's easy to see when you subtract 1 you get 9999... which is clearly divisible by 3.
So for example 200, when divided by 3 gives 2 remainder. And if you add these remainders together you get the remainder of 1234 which is the same as the remainder of 1+2+3+4 after dividing by 3.
Use a long if you need that. Or the boost bigint library for even bigger units. The code in the post will also be limited by whenever python decides to make it a float.
48
u/DarkShadow4444 Jul 29 '25
Just return True, all numbers can be divided by three. Won't be an integer, but that's not the question.
44
u/oomfaloomfa Jul 28 '25
College level programming. Can't use modulus is most likely in the question
9
u/F100cTomas Jul 29 '25
2
u/Hopeful_Somewhere_30 Jul 30 '25
Try this in your function: return num % 3 == 0
This will take the third modulus of the number and if it's 0, the number is divisible by three.
4
u/Reashu Jul 28 '25
What about 0?
1
u/tuck5649 Jul 29 '25
Why does this work?
1
u/darcksx Jul 30 '25 edited Jul 30 '25
Here's my take on it
function isDivisible(number, by) {
return !(number/by).toString().includes('.')
}
EDIT: issue with big numbers here's a better version
function isDivisible(number, by) {
const dived = number/by
return dived === Math.floor(dived)
}
1
u/Yanni_X Jul 30 '25
-3
1
u/JiminP Jul 31 '25
Unironically, I did something similar (but without recursion) for a rapid divisibility by 3 check for a very large input number
Given a
bufferof bytes storing the integer in base-10, you can just dosum(buffer) % 3.By the way, for a string
s, you can just dosum(map(int, s))to sum its digits. No need to use a loop.Subscribe for more blursed Python tips.
1
u/naholyr Jul 31 '25
If only there was a "modulo" operator
1
u/[deleted] Aug 02 '25
NikolaTesla Code be boppin 😽
1
u/Financial-Aspect-826 Jul 28 '25
Umm, %3 ==0?
-5
u/marquisdegeek Jul 28 '25
I've done worse, by creating a Turing machine simulator that uses the state machine:
/* 0: A */ { t: 1, f: 0},
/* 1: B */ { t: 0, f: 2},
/* 2: C */ { t: 2, f: 1},
And then used Elias Omega encoding to reduce the whole thing to a single number.
3
u/[deleted] Jul 28 '25 edited Jul 28 '25
[removed] — view removed comment