To solve this problem, we need to determine the number of distinct prime numbers that can be formed using the digits of a given input number. The solution involves generating all possible permutations of the digits (of any length) and checking each permutation for primality, while ensuring we count only unique primes.
Approach
- Prime Check Function: First, we need a helper function to check if a number is prime. This function efficiently checks for primality by testing divisibility up to the square root of the number.
- Generate Permutations: For each possible length from 1 to the length of the input number, generate all permutations of the digits.
- Filter Valid Numbers: Skip permutations with leading zeros (except for single-digit zero, which is not prime).
- Collect Unique Primes: Use a set to collect all valid primes to avoid duplicates.
- Count Primes: The size of the set gives the number of distinct primes.
Solution Code
import itertools
def is_prime(n):
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n ** 0.5) + 1, 2):
if n % i == 0:
return False
return True
def count_distinct_primes(s):
primes = set()
length = len(s)
for l in range(1, length + 1):
for perm in itertools.permutations(s, l):
num_str = ''.join(perm)
if len(num_str) > 1 and num_str[0] == '0':
continue
num = int(num_str)
if is_prime(num):
primes.add(num)
return len(primes)
# Read input and output the result
input_str = input().strip()
print(count_distinct_primes(input_str))
Explanation
- Prime Check: The
is_primefunction checks if a number is prime by first handling small cases (0,1,2) and then testing divisibility by odd numbers up to the square root of the number. This ensures efficiency. - Permutations: Using
itertools.permutations, we generate all possible sequences of digits of varying lengths. This covers all possible numbers that can be formed from the input digits. - Leading Zeros: We skip permutations that start with zero (for lengths greater than 1) since these are not valid numbers (e.g., "03" is not a valid 2-digit number).
- Unique Primes: Using a set to store primes ensures that even if different permutations result in the same prime number, it is counted only once.
- Result: The size of the set of primes gives the count of distinct primes that can be formed from the input digits.
This approach efficiently handles all edge cases (like duplicate digits, leading zeros, and small numbers) and provides the correct count of distinct primes. The use of sets ensures we avoid duplicates, and the prime check is optimized for performance.


(免责声明:本文为本网站出于传播商业信息之目的进行转载发布,不代表本网站的观点及立场。本文所涉文、图、音视频等资料的一切权利和法律责任归材料提供方所有和承担。本网站对此资讯文字、图片等所有信息的真实性不作任何保证或承诺,亦不构成任何购买、投资等建议,据此操作者风险自担。) 本文为转载内容,授权事宜请联系原著作权人,如有侵权,请联系本网进行删除。