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 the implementation of the above method
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
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. See following Wiki page for details.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Check divisibility in a binary stream
- To check divisibility of any large number by 999
- Check if a large number is divisibility by 15
- Check the divisibility of Hexadecimal numbers
- Sub-string Divisibility by 3 Queries
- Sub-string Divisibility by 11 Queries
- Maximum path sum for each position with jumps under divisibility condition
- Divisibility by 12 for a large number
- Repeated Unit Divisibility
- Divisibility by 3 where each digit is the sum of all prefix digits modulo 10
- Maximize profit when divisibility by two numbers have associated profits
- Divisibility by 64 with removal of bits allowed
- Check if a number is multiple of 5 without using / and % operators
- Check whether a given point lies inside a triangle or not
- How to check if two given line segments intersect?
- How to check if a given point lies inside or outside a polygon?
- How to check if a given number is Fibonacci number?
- Check if a number is multiple of 9 using bitwise operators
- Check if binary representation of a number is palindrome
- How to check if an instance of 8 puzzle is solvable?