Challenge: Manasa loves Maths
Subdomeniu: Number Theory (number-theory)
Scor cont: 50.0 / 50
Submission status: Accepted
Submission score: 1.0
Submission ID: 464739475
Limbaj: python3
Link challenge: https://www.hackerrank.com/challenges/manasa-loves-maths/problem
Cerinta
You are given an integer N. Is there a permutation of digits of integer that's divisible by 8? A permutation of digits of integer N is defined as an integer formed by rearranging the digits of N. For example, if the number N = 123, then {123, 132, 213, 231, 312, 321} are the possible permutations.
**Input Format**
The first line contains an integer _T_ i.e. number of test cases.
_T_ lines follow, each containing the integer _N_.
**Output Format**
For each test case print `YES` if there exists one such re-arrangement of N such that it is divisible by 8 or `NO` if there isn't.
**Constraints**
1 <= T <= 45<br>
0 <= N <= 10<sup>110</sup>
**Note**
Re-arrangements of _10_ are _{10, 01}_ which boils down to _{10, 1}_.
**Sample Input**
2
61
75
**Sample Output**
YES
NO
**Explanation**
_Test case #00:_ 16 is permutation of 61 which is divisible by 8.
_Test case #01:_ None of permutation of 75, {57, 75}, are divisible by 8.
Cod sursa
import sys
from collections import Counter
# Precompute digit requirements for all 3-digit multiples of 8.
MULTS = []
for x in range(0, 1000, 8):
s = f"{x:03d}"
MULTS.append(Counter(s))
def can_div_by_8(num_str: str) -> bool:
n = num_str.strip()
if len(n) == 1:
return int(n) % 8 == 0
if len(n) == 2:
a = int(n)
b = int(n[::-1])
return (a % 8 == 0) or (b % 8 == 0)
c = Counter(n)
for need in MULTS:
ok = True
for d, cnt in need.items():
if c[d] < cnt:
ok = False
break
if ok:
return True
return False
def main():
data = sys.stdin.read().strip().split()
if not data:
return
t = int(data[0])
out = []
for i in range(1, t + 1):
out.append('YES' if can_div_by_8(data[i]) else 'NO')
sys.stdout.write('\n'.join(out))
if __name__ == '__main__':
main()
HackerRank Number Theory – Manasa loves Maths
