![]() |
VOOZH | about |
Given a number n, the task is to check if it is divisible by 7 or not.
Note: You are not allowed to use the modulo operator, floating point arithmetic is also not allowed.
Examples:
Input: n = 371
Output: True
Explanation: 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.Input: n = 7673
Output: False
Explanation: The number 7673: 767 - (2×3) = 767 - 6 = 761; 76 - (2 × 1) = 76 - 2 = 74; 7 - (2 × 4) = 7 - 8 = -1; thus, since -1 is not divisible by 7, 7673 is not divisible by 7.
Table of Content
A simple method is repeated subtraction.
n.True
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.
True
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 + 2band multiplying by -1 gives
a - 2bTime Complexity: O(log10n) The number of digits in the number is the no of times the iteration occurs.
If suppose the number given is very large like 10100000 then you can take input in the form of string and can use a-2b approach using addition and subtraction of strings, but then the complexity will be O(n2), where n is the length of the number.
Space Complexity: O(1)