![]() |
VOOZH | about |
Given a large positive number as string, count all rotations of the given number which are divisible by 8.
Examples:
Input: 8
Output: 1
Input: 40
Output: 1
Rotation: 40 is divisible by 8
04 is not divisible by 8
Input : 13502
Output : 0
No rotation is divisible by 8
Input : 43262488612
Output : 4
It is difficult to rotate and divide each number by 8 for large numbers. Therefore, the "divisibility by 8" property says that a number is divisible by 8 if the last 3 digits of the number is divisible by 8. Here we do not rotate the number and check the last 8 digits for divisibility, instead, we count consecutive sequences of 3 digits (in a circular way) which are divisible by 8.
Consider a number 928160
Its rotations are 928160, 092816, 609281,
160928, 816092, 281609.
Now form consecutive sequence of 3-digits from
the original number 928160 as mentioned in the
approach.
3-digit: (9, 2, 8), (2, 8, 1), (8, 1, 6),
(1, 6, 0),(6, 0, 9), (0, 9, 2)
We can observe that the 3-digit number formed by
the these sets, i.e., 928, 281, 816, 160, 609, 092,
are present in the last 3 digits of some rotation.
Thus, checking divisibility of these 3-digit numbers
gives the required number of rotations.
Rotations: 4
Please refer complete article on Count rotations divisible by 8 for more details!