Soluție HackerRank pentru Manasa loves Maths, subdomeniul Number Theory, în Python 3. Include cerința formatată, exemple, explicația pașilor și cod sursă.

  • Problemă: Manasa loves Maths
  • Domeniu: Number Theory
  • Limbaj: Python 3

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

Cerință

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

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 sursă

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