Given an integer N, the task is to check if it is divisible by 8 without using % operator or / operator or any bitwise operator.
Examples :
Input : 34232 Output : True Input : 541 Output : False
Approach :
The idea is to use the fact that 1000 is always divisible by 8, so we can only check the last three digits
Construct a HashSet that will store all the numbers which are divisible by 8.
Convert the given integer to a string.
If the length of the string is less than 4, check if the number is present in the HashSet or not. If the number is present is in the HashSet then we return True otherwise False.
Get the last three-digit number from the given number.
If the last three-digit number exists in the HashSet then we return True otherwise False.
Implementation :
# To check if the number is divisible by 8 or not
def isDiv(n):
# creating the set of numbers
# that are divisible by 8
hashset = set()
for i in range(0,1001,8):
hashset.add(i)
strN = str(n)
if len(strN) <= 3:
if n in hashset:
return True
return False
# getting the last three digits
last3 = strN[len(strN)-3:]
if int(last3) in hashset:
return True
return False
# Driver Code
N = 34232
# To display the result
print(isDiv(N))
Output : True
Time Complexity : O(1)
Auxiliary Space : O(1)