Search code examples
divisionmodulointeger-division

Check if a number is divisible by 3


I need to find whether a number is divisible by 3 without using %, / or *. The hint given was to use atoi() function. Any idea how to do it?


Solution

  • Subtract 3 until you either

    a) hit 0 - number was divisible by 3

    b) get a number less than 0 - number wasn't divisible

    -- edited version to fix noted problems

    while n > 0:
        n -= 3
    while n < 0:
        n += 3
    return n == 0