Problem: Divisible by 8

Given a number, you need to check whether any permutation of the number is divisible by 8 or not. Print Yes or No.

Input:
The first line of input contains a single integer T denoting the number of test cases. Then T test cases follow. Each test case consist of one line. The first line of each test case consists of an integer N.

Output:
Corresponding to each test case, in a new line, print Yes if divisible by 8, else No.

Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 100000

Example:

Input
2
46
345

Output
Yes
No

A number is divisible by 8 if the last 3 digits of it divisible by 8.
First I create a dictionary of numbers that divisible by 8, and store them as string. Then I generate all permutations length 3 of the input number, and check if that permutations is in the dictionary.

Python 2.7:

from itertools import *
if __name__ == '__main__':
    dic = set()
    """
    abc, acb, cab, cba, bac, bca
    """
    for _ in range(0, 1000, 8):
        if _ < 10:
            dic.add("00"+str(_))
        elif _ < 100:
            dic.add("0"+str(_))
        else:
            dic.add(str(_))

    t = input()
    for _ in range(t):
        n = input()
        if n < 10:
            n = '00' + str(n)
        elif n < 100:
            n = '0' + str(n)
        else:
            n = str(n)
        
        for x in list(permutations(n, 3)):
            if ''.join(x) in dic:
                print "Yes"
                break
        else:
            print "No"
    

 

Advertisements