
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if any permutation of a large number is divisible by 8 in Python
Divisibility By 8
According to the divisibility rule of 8, if the last three digits of a number are divisible by 8, then the entire number is divisible by 8. While this is easy to check for small numbers, when it comes to large numbers, generating all the possible permutations is impractical for large inputs.
However, we can solve this problem by taking advantage of the divisibility rule and limiting our check to possible combinations of three digits.
Scenario 1
Input: "61" Output: Yes Explanation: For the given input, the possible permutations of the digits are 16 and 61. Among them, 16 is divisible by 8 (16/8=2). Hence, its permutation is divisible by 8.
Scenario 2
Input: "111" Output: No Explanation: For the given input, the only possible permutation is 111. Since 111/8= 13.8, it is not divisible by 8, as no other permutations exist with different digits. Hence, the answer is no.
Let's dive into the example to understand more about checking if any permutation of a large number is divisible by 8.
Example: Divisibility by 8 Using Python
In the following example, we are going to consider the input as "61" and check whether the permutation of a large number is divisible by 8.
from itertools import permutations from collections import Counter def demo(num: str) -> str: x = len(num) if x <= 3: y = set(permutations(num)) for p in y: z = int(''.join(p)) if z % 8 == 0: return "Yes" return "No" a = [str(i).zfill(3) for i in range(0, 1000, 8)] b = Counter(num) for val in a: c = Counter(val) if all(b[d] >= c[d] for d in c): return "Yes" return "No" input_number = "61" result = demo(input_number) print("Input:", input_number) print("Output:", result)
Following is the output of the above program:
Input: 61 Output: Yes
Conclusion
Checking if any permutation of a large number is divisible by 8 can be solved without brute-forcing every possibility. By using the divisibility rules and Python's collections.Counter we can build a solution that works well for large inputs.