Given a number, check if it is divisible by 7. You are not allowed to use modulo operator, floating point arithmetic is also not allowed.

A simple method is repeated subtraction. Following is another interesting method.

Divisibility by 7 can be checked by a recursive method. A number of the form 10a + b is divisible by 7 if and only if a – 2b is divisible by 7. In other words, subtract twice the last digit from the number formed by the remaining digits. Continue to do this until a small number.

Example: the number 371: 37 – (2×1) = 37 – 2 = 35; 3 – (2 × 5) = 3 – 10 = -7; thus, since -7 is divisible by 7, 371 is divisible by 7.

Following is C implementation of the above method

[pastacode lang=”c” manual=”%2F%2F%20A%20Program%20to%20check%20whether%20a%20number%20is%20divisible%20by%207%0A%23include%20%3Cstdio.h%3E%0A%20%0Aint%20isDivisibleBy7(%20int%20num%20)%0A%7B%0A%20%20%20%20%2F%2F%20If%20number%20is%20negative%2C%20make%20it%20positive%0A%20%20%20%20if(%20num%20%3C%200%20)%0A%20%20%20%20%20%20%20%20return%20isDivisibleBy7(%20-num%20)%3B%0A%20%0A%20%20%20%20%2F%2F%20Base%20cases%0A%20%20%20%20if(%20num%20%3D%3D%200%20%7C%7C%20num%20%3D%3D%207%20)%0A%20%20%20%20%20%20%20%20return%201%3B%0A%20%20%20%20if(%20num%20%3C%2010%20)%0A%20%20%20%20%20%20%20%20return%200%3B%0A%20%0A%20%20%20%20%2F%2F%20Recur%20for%20(%20num%20%2F%2010%20-%202%20*%20num%20%25%2010%20)%20%0A%20%20%20%20return%20isDivisibleBy7(%20num%20%2F%2010%20-%202%20*%20(%20num%20-%20num%20%2F%2010%20*%2010%20)%20)%3B%0A%7D%0A%20%0A%2F%2F%20Driver%20program%20to%20test%20above%20function%0Aint%20main()%0A%7B%0A%20%20%20%20int%20num%20%3D%20616%3B%0A%20%20%20%20if(%20isDivisibleBy7(num%20)%20)%0A%20%20%20%20%20%20%20%20printf(%20%22Divisible%22%20)%3B%0A%20%20%20%20else%0A%20%20%20%20%20%20%20%20printf(%20%22Not%20Divisible%22%20)%3B%0A%20%20%20%20return%200%3B%0A%7D” message=”C program” highlight=”” provider=”manual”/]

Output:

Divisible
[ad type=”banner”]

How does this work? Let ‘b’ be the last digit of a number ‘n’ and let ‘a’ be the number we get when we split off ‘b’.
The representation of the number may also be multiplied by any number relatively prime to the divisor without changing its divisibility. After observing that 7 divides 21, we can perform the following:

 10.a + b

after multiplying by 2, this becomes

 20.a + 2.b

and then

 21.a - a + 2.b

Eliminating the multiple of 21 gives

 -a + 2b

and multiplying by -1 gives

 a - 2b

There are other interesting methods to check divisibility by 7 and other numbers.

[ad type=”banner”]