We need to count positive divisors d of x such that d and x share at least one common digit in decimal representation.
Constraints: T up to 100, x up to 1e9. That's manageable. For each test case, we can compute all divisors of x (which can be up to around 134k divisors for numbers up to 1e9? Actually maximum number of divisors for numbers ≤ 1e9 is around 1344? Let's check: The maximum number of divisors for n ≤ 1e9 is 1536? I recall that for 10^9, maximum d(n) is around 1344. For 73513440 (near 10^7) it's 1344. Actually the number with most divisors under 1e9 is 73513440 with 1344 divisors. There might be numbers with up to around 1536 divisors under 1e9? Let's recall: 73513440 has 1344 divisors. For 10^9, the known champion is 73513440? Actually 73513440 is about 7.35e7, not near 1e9. There might be numbers like 963761198400? That's > 1e9. So under 1e9, I think the maximum divisor count is 1536? Let's quickly check: 2^9 * 3^4 * 5^2 * 7 * 11 * 13 * 17 is > 1e9? 2^9=512, 3^4=81, 5^2=25, product 51281=41472, 25=1,036,800, 7=7,257,600, 11=79,833,600, 13=1,037,836,800, 17=17,645,225,600 which exceeds 1e9. So maybe 2^8 * 3^4 * 5^2 * 7 * 11 * 13 * 17 = 25681257111317 = 256*81=20736, *25=518400, *7=3,628,800, *11=39,916,800, *13=518,918,400, *17=8,821,612,800 > 1e9. So maybe the maximum is around 1344. Actually there is known sequence: Highly composite numbers. For 10^9, the HCN with max divisors is 73513440 (with 1344 divisors). Also 963761198400 has 6720 divisors but >1e9. So 1344 is plausible. So we can enumerate all divisors of x by factoring x (since x ≤ 1e9, we can factor via trial division up to sqrt(x) which is 31623, that's okay for up to 100 test cases = 3.16 million divisions worst-case, which is fine in typical time limits (1 second maybe a bit high but likely okay in Python if optimized? Might be okay with precomputed primes up to 31623 using sieve; then factoring each number with primes up to sqrt(n) will be fast, worst-case about 3401 primes up to 31623, times 100 = 340k operations, very fast. Then generate divisors via recursive combination. Then for each divisor, check if it shares any digit with x. Count those. That yields answer.
But we might need to be careful about time; but 100 * 1344 ≈ 134,400 divisor checks, each digit check trivial, overall fine.
Edge cases: x=1, divisors: {1}. digits: {1}. They share digit 1, so answer 1. For 10, divisors: 1,2,5,10. Digits of x: {1,0}. Check: 1 has digit 1 => shares; 2 digits {2} none; 5 none; 10 digits {1,0} shares both 1 and 0? Actually 10 shares digits 1 and 0, so shares. So answer 2.
Implementation steps:
- Precompute list of primes up to 31623 (sqrt(1e9) ≈ 31622.776) using sieve.
- For each test case:
- Read x.
- Factor x: produce dictionary of prime->exponent.
- Generate list of divisors: recursively iterate over prime factors, multiply combinations.
- Convert x to string: sx = str(x). Compute set of digits of x: set(sx).
- For each divisor d, convert to string sd = str(d). Check if any char in sd in set_x. If yes, increment count.
- Print count.
Alternatively, we could compute divisor count directly by checking each divisor candidate and digit condition without generating full list, but generating divisors is fine.
Potential optimization: For x up to 1e9, number of divisors is at most 1344; generating all divisors might be done via product of (exponents+1) combos. Efficient recursion.
Edge: For x large prime, divisors: 1 and x. 1 always shares? Only if x contains digit '1'. But if x is prime and does not contain 1, then only x itself shares? Actually check: d=1; digits of 1 is '1'. Does x contain 1? If not, then no. d=x always shares because it's the same number, so digits are identical, thus at least one common digit. So answer at least 1 (the divisor x itself). So answer always at least 1.
But careful: If x is 0? Not allowed; x positive.
Implementation details:
- Function generate_divisors(factors): start with [1]. For each (p, e), for each current value in list, multiply by p^exp for exp from 1 to e. Could use iterative: divisors = [1]; for p, e in factors.items(): new_divisors = [] for d in divisors: v = d for i in range(e+1): new_divisors.append(v); v *= p? Actually careful: For each p, we need to multiply existing divisors by p^0, p^1,..., p^e. So we can do: tmp = [] for d in divisors: cur = d for i in range(e+1): tmp.append(cur); cur *= p. Then set divisors = tmp.
But note order: need to avoid duplicates, but since p are distinct primes, fine.
Now note that we need only positive divisors; x itself will be included.
Complexities: fine.
Let's double-check sample: works.
We might consider alternative approach: for each digit in x, count divisors containing that digit and use inclusion-exclusion? But simpler to generate divisors.
However, generating divisors via recursion can produce large lists but limited.
Edge Cases:
Implementation in Python:
Precomputation:
import sys
import math
def sieve(limit):
is_prime = [True] * (limit+1)
is_prime[0] = is_prime[1] = False
for i in range(2, int(limit**0.5)+1):
if is_prime[i]:
step = i
start = i*i
is_prime[start:limit+1:step] = [False] * ((limit - start)//step + 1)
primes = [i for i, v in enumerate(is_prime) if v]
return primes
primes = sieve(31623) # sqrt(10^9) ~ 31623
But careful: The slice assignment with list multiplication might be okay but we can use simple loop.
Alternatively use typical sieve.
Factoring:
def factorize(n):
factors = {}
temp = n
for p in primes:
if p*p > temp:
break
if temp % p == 0:
cnt = 0
while temp % p == 0:
temp //= p
cnt += 1
factors[p] = cnt
if temp > 1:
factors[temp] = 1
return factors
Then generate divisors:
def get_divisors(factors):
divisors = [1]
for p, e in factors.items():
current_len = len(divisors)
multiplier = 1
for exp in range(1, e+1):
multiplier *= p
for i in range(current_len):
divisors.append(divisors[i] * multiplier)
return divisors
Wait: The above approach: For each prime, we need to multiply existing divisors by p^1, p^2,..., p^e. The typical way:
divs = [1]
for p, e in factors.items():
divs = [d * (p ** k) for d in divs for k in range(e+1)]
But that could be less efficient due to repeated exponentiation. But we can do:
divs = [1]
for p, e in factors.items():
cur = []
pe = 1
for k in range(e+1):
for d in divs:
cur.append(d * pe)
pe *= p
divs = cur
Yes.
Now for each test case, compute divisors, then count.
But is there any more efficient approach? Maybe we could avoid generating all divisors by iterating over i from 1 to sqrt(x) and check if i divides x, then consider both i and x//i. Since number of divisors is ~ up to 1344, but iterating up to sqrt(x) (31623) per test case is also acceptable for T=100? 100 * 31623 = 3.16 million, which is also okay. And we avoid factoring and generating divisors. That might be simpler: For each test case, loop i from 1 to int(sqrt(x)). If x % i == 0: then we have two divisors: i and x//i (if i != x//i). For each, check if share digit. Count. This is straightforward and easier to code. Complexity: For each test case, up to sqrt(x) = 31623 iterations, each with modulo operation and string conversion? That's about 3 million modulo ops, which is fine. However, for T=100, it's 3.16 million operations; that's trivial. But wait: For each divisor we need to check digit sharing. That's okay. However, careful: For numbers like 10^9, sqrt = 31622.776, loop 31623 times. 100 * 31623 ≈ 3.16 million, fine.
But there is a subtlety: For each i we need to compute digits of i and check against set of digits of x. Converting each i to string for digit check might be a bit overhead, but still fine (3 million conversions). Might be okay in Python within time limit (like 1-2 seconds). However, there is a risk if T=100 and each x is large prime (so loop all the way to sqrt). 3 million loops is fine.
But to be safe, we can precompute set of digits of x once. Then for each divisor i, we can check digits by converting to string and iterating.
Alternatively, we could compute digit bitset as a bitmask (10 bits) and for each divisor compute its mask and check intersection. That could be faster. For each divisor, we can compute its digit mask by repeatedly taking modulo 10. That's also okay.
Simplest: Loop i=1 to sqrt(x). If x % i == 0: then for each divisor d in (i, x//i) if d is not counted twice, check if share digits. We need to store visited divisors? Actually we count each divisor once. If i != x//i, we count both. So we can just increment count.
But there is a potential issue: For x up to 1e9, sqrt is about 31623, so loop is fine. However, note that the number of divisors we process is twice the number of i up to sqrt, but we only do full work for those i where x % i == 0. That's at most sqrt(x) checks anyway. So the total operations is roughly sqrt(x) modulo divisions plus a few string conversions for actual divisors (which are at most number of divisors, around 1344, not sqrt). Actually careful: In the loop from 1 to sqrt(x), we must do modulo check for each i. That is ~31623 per test case. Then for each divisor we find, we do digit check. So overall per test case: 31623 modulo ops + up to 1344 digit checks. That's fine.
Thus we can implement this simpler solution without factoring. This is more straightforward and less error-prone.
But we have to be careful: For numbers like 10^9, sqrt=31622.77, we loop 31623 times, each modulo operation may be cheap. For T=100, 3.16 million modulo ops, definitely okay.
So algorithm per test case:
- Read x.
- Convert x to string: sx = str(x); create set digits_x = set(sx). Or create a boolean array of length 10: digit_present[10] = False for each digit in sx.
- ans = 0.
- For i from 1 to int(sqrt(x)):
- if x % i == 0:
d1 = i
d2 = x // i
if shares(d1): ans += 1
if d2 != d1 and shares(d2): ans += 1
- Print ans.
Define shares(d):
- Convert d to string or iterate digits; check if any digit in digits_x.
To optimize shares, we can compute digit mask of d: while d>0: digit = d%10; if digit present in digits_x then return True; d//=10. But we have to be careful: d can be 0? No, positive integers. So fine.
Alternatively, convert to string and use any(c in digits_x for c in str(d)). Might be slower but still fine.
Given small number of divisors, either works.
But note that in the loop we call shares on each divisor. There are at most about 1344 calls per test case. So it's fine.
So we implement.
Edge case: x=1. sqrt=1. i=1: x%1=0. d1=1, d2=1. shares(1) true? digits_x = {'1'}; so ans+=1; d2==d1, so skip second. answer=1. Good.
Implementation details:
-
Use math.isqrt to get integer sqrt safely (Python 3.8+). Or int(math.sqrt(x)) but float inaccuracies for large numbers; better use math.isqrt.
-
For i in range(1, isqrt(x)+1): etc.
Potential improvement: The loop up to sqrt(x) may be done for each test case separately; T=100, so total 3.16M loops. That's fine.
But if time limit is very strict, we could factor and generate divisors which yields less than 1344 divisors, but the overhead of factoring might be similar or less? Actually factoring via trial division up to sqrt(x) using precomputed primes will need checking primes up to sqrt(x) (about 3400 primes) per test case, which is less than 31623 loops. So factoring using primes could be more efficient if T=100 and we want to minimize operations. But 31623 loops per test case is still small. However, in Python, 3 million loops are okay within a second typically. With modulo and condition, maybe about 0.1-0.2 seconds? Actually 3 million simple operations might be ~0.03-0.05 secs? Not sure, but typical Python can do ~50 million simple operations per second? Actually Python's loop overhead is high. 3 million loops with a few operations each might be around 0.2-0.3 seconds, still okay. Combined with 100 test cases might be ~0.3 seconds? Actually 100 * 31623 = 3,162,300 loops. Each loop does: check x % i == 0 (mod operation). That's moderately heavy but still okay. In worst-case, maybe 0.5 seconds. Should pass typical 1 or 2 sec time limit.
But factoring with primes would reduce loops to about 3400 per test case (primes list size ~3401). Then generating divisors adds some overhead. That's even faster. So we might prefer factoring to be safe. But both fine.
I'll implement factoring using trial division with primes up to sqrt(x). That's more efficient.
We need to precompute primes up to 31623 using sieve. This one-time cost is negligible.
Implementation plan in code:
import sys
import math
def generate_primes(limit):
sieve = [True] * (limit+1)
sieve[0] = sieve[1] = False
for i in range(2, int(limit**0.5) + 1):
if sieve[i]:
sieve[i*i: limit+1: i] = [False] * ((limit - i*i) // i + 1)
return [i for i, is_p in enumerate(sieve) if is_p]
PRIMES = generate_primes(31623)
def factorize(n):
factors = {}
temp = n
for p in PRIMES:
if p * p > temp:
break
if temp % p == 0:
cnt = 0
while temp % p == 0:
temp //= p
cnt += 1
factors[p] = cnt
if temp > 1:
factors[temp] = 1
return factors
def gen_divisors(factors):
divisors = [1]
for p, exp in factors.items():
new_divs = []
mul = 1
for e in range(exp+1):
for d in divisors:
new_divs.append(d * mul)
mul *= p
divisors = new_divs
return divisors
def has_common_digit(a, digit_set):
while a > 0:
if a % 10 in digit_set:
return True
a //= 10
return False
def solve():
import sys
data = sys.stdin.read().strip().split()
if not data:
return
it = iter(data)
t = int(next(it))
out_lines = []
for _ in range(t):
x = int(next(it))
# compute digit set of x
digit_set = set()
tmp = x
while tmp > 0:
digit_set.add(tmp % 10)
tmp //= 10
# special: x=0? not possible.
# Factor x and get divisors
factors = factorize(x)
divisors = gen_divisors(factors)
count = 0
for d in divisors:
if has_common_digit(d, digit_set):
count += 1
out_lines.append(str(count))
sys.stdout.write("\n".join(out_lines))
if __name__ == "__main__":
solve()
Check: For x=10, factors: {2:1,5:1}, divisors: [1,2,5,10]. digit_set for x: {0,1}. has_common_digit(1): digits {1}? while loop: 1%10=1 in set => True => count1; 2: 2%10=2 not in set => false; 5: 5%10=5 not; 10: 10%10=0 in set => True; count=2.
Works.
Edge: x=0 not allowed.
But note: For x that are perfect squares, divisor generation includes sqrt twice? No, we generate via combinations, each divisor exactly once. So fine.
Potential inefficiency: In gen_divisors, we compute for each prime factor, we iterate over current divisors list and multiply by powers. This can be memory heavy if number of divisors is large (1344), but that's fine.
We used while loop to compute digit set of x: I used mod. But set(str(x)) is simpler. However, mod is fine.
But careful: In while loop for digit_set we used while tmp > 0: .... For x=0, we would have empty set, but x≥1.
Now, about the has_common_digit function: It uses while a > 0. For a=0? Not possible because divisors are positive. For a with digit 0? Actually a%10 yields 0. If 0 is in digit_set, then returns true. That's correct. However, if x contains digit 0, then any divisor that ends with 0 or contains 0 will be counted. The while loop will break when a becomes 0, so it checks digits from least significant. That's fine.
But note: For divisor like 10, while loop: a=10 → a%10=0 (check), true. So correct.
Now what about divisor like 100? digits: 1,0,0. Check 0 will be found.
Edge: For divisor that is 0? Not possible.
Now, for x containing digit 0, we should also consider divisor 0? No.
Now, for x containing digit 0, we need to check if divisor contains 0. Our has_common_digit function works.
Now consider x=1000000000 (1e9). digit_set includes 1 and 0. Divisors include numbers with trailing zeros, so many will contain 0. So count may be high.
But that's okay.
Complexities are fine.
Now, we must consider potential pitfalls: Factorization: For large prime near 1e9, after trial division with all primes up to sqrt, we will break only when p*p > temp. Since we loop over all primes up to sqrt(x). For prime x, we will iterate over all primes up to sqrt(x) ~31623. There are about 3401 primes in that range. That's fine. Then we will have temp >1, so we add as factor. So factoring is O(number of primes up to sqrt) ~3400 per test case.
Now, divisor generation: For prime, factors = {p:1}, divisors = [1, p] length 2. So quick.
Thus total operations: For each test case, up to 3400 division checks, then generating divisors (small). So total for 100 cases: about 340k operations, plus digit checks: about 2 per divisor? Actually maybe up to 1344 per case, but still small.
Thus this solution is efficient.
Now test with given sample:
Input:
2
1
10
We compute:
Case1: x=1, digit_set = {1}. factors: factorize(1): After loop, pp > 1? Initially temp=1, loop condition pp > temp? For first p=2, 2*2=4 >1, break. Then if temp>1? temp=1, not >1, factors empty. Then gen_divisors(factors) should return [1] because start with [1] and loop over empty items, so remains [1]. Then check has_common_digit(1,{1}) -> true. count=1.
Case2: as above -> 2.
Matches.
Now we should consider any corner cases:
-
x = 2: divisors 1,2. digit_set {2}. Check: 1 (digit 1) not in set; 2 -> true. count=1.
-
x = 3: similar.
-
x = 11: divisors 1,11. digit_set {1}. Check: 1 -> true (digit 1 in set). 11 -> digits 1,1 both in set => true. count=2.
-
x = 101: divisors? 101 prime? 101 is prime? Actually 101 is prime. divisors 1 and 101. digit_set {1,0}. 1 shares 1; 101 shares 1 and 0? Actually 101 contains digits 1,0,1; both in set => true. count=2.
-
x = 20: divisors: 1,2,4,5,10,20. digit_set {2,0}. Check: 1->false; 2->true; 4->false;5->false;10->0 true;20->2 and 0 true => true. count=3 (2,10,20). But wait also 20 itself, and also maybe 2? Yes 3.
Now implement.
We must ensure that we correctly handle numbers with repeated digits and zeros.
Now, what about digit set representation? We used set of ints (0-9). In has_common_digit we compute a%10 and check membership. That's correct.
Now, we need to be careful with reading input: Use sys.stdin.read for speed.
Now, confirm sieve method: Use list assignment to set multiples to False. However, careful with large slices; it's okay.
Alternatively, we could use a simple sieve:
limit = 31623
is_prime = [True] * (limit+1)
is_prime[0] = is_prime[1] = False
for i in range(2, int(limit**0.5)+1):
if is_prime[i]:
for j in range(i*i, limit+1, i):
is_prime[j] = False
primes = [i for i, val in enumerate(is_prime) if val]
This is safe.
Now, we should also note that when factoring, after the loop, temp may be a large prime > sqrt(original n). For numbers up to 1e9, temp will be at most 1e9, but if it's composite with a factor > sqrt(n), that's impossible because there can be only one factor > sqrt(n), and it must be prime (or product of two > sqrt? impossible). So it's either 1 or a prime. So we can treat it as prime.
Now, we might have x=0? Not.
Now, check performance: The precomputation of primes up to 31623 is done once. The factorize uses for p in primes: if p*p > temp: break. So it will break early for numbers that become small after factoring out small primes. For composite numbers, it's fast.
Thus solution is efficient.
Now, we must also consider that generating divisors with the method above may produce unsorted list, but we don't need sorting.
Now, I'll produce final answer.
But there is one nuance: In the gen_divisors function, we used new_divs = [] and then appended. This can cause many list expansions but okay.
Alternate: Use list comprehension: divisors = [d * mul for d in divisors for mul in (p**e for e in range(exp+1))] but that's messy.
Now, final code.
I'll write the final answer accordingly.
But wait: In the problem statement, they say "d is the divisor of x, and x and d have at least one common (the same) digit in their decimal representations." That means they share at least one digit. Our check does that.
Now, note: For divisor d, it could be equal to x, always shares all digits, so counted.
Now, output the answer per test case.
Now, we should consider potential issues: integer division, handling large exponents: Not a problem.
Now, one more optimization: For the digit set, we could use a boolean list of 10 instead of set. That might be slightly faster. But not needed.
Let's convert digit_set to a 10-element boolean list for quick lookup.
I'll implement digit_present = [False]*10; while x>0: digit_present[x%10]=True; x//=10. But we need x later for factorization, so we store original x in variable n.
Better: compute digit_present from x before factorization? But we need x for factorization anyway. So we can keep n = x. Then compute digit_present while iterating over n (we can use a copy). Or simply use str: digits = str(x) and build set. That's simpler and less error-prone. But using integer mod may be slightly faster.
I'll use boolean list:
n = x
digit_present = [False]*10
if n == 0: digit_present[0]=True # not needed
while n > 0:
digit_present[n%10] = True
n //=10
But we need n for factorization? We still have original x. So we can do:
original = x
digit_present = [False]*10
temp = original
while temp:
digit_present[temp%10] = True
temp //=10
Now factorization uses original.
Now has_common_digit: pass digit_present list:
def has_common(d, dp):
while d>0:
if dp[d%10]:
return True
d //=10
return False
Edge: d might be 0? No.
Now, we need to handle d that might be 0? Not possible.
Now, incorporate.
Now, final code:
import sys, math
def sieve(limit):
is_prime = [True]*(limit+1)
is_prime[0]=is_prime[1]=False
for i in range(2, int(limit**0.5)+1):
if is_prime[i]:
for j in range(i*i, limit+1, i):
is_prime[j]=False
return [i for i,val in enumerate(is_prime) if val]
PRIMES = sieve(31623)
def factorize(n):
factors = {}
temp = n
for p in PRIMES:
if p*p > temp:
break
if temp % p == 0:
cnt = 0
while temp % p == 0:
temp //= p
cnt += 1
factors[p] = cnt
if temp > 1:
factors[temp] = 1
return factors
def gen_divisors(factors):
divs = [1]
for p, exp in factors.items():
new_divs = []
mul = 1
for _ in range(exp+1):
for d in divs:
new_divs.append(d * mul)
mul *= p
divs = new_divs
return divs
def solve():
data = sys.stdin.read().strip().split()
if not data:
return
it = iter(data)
t = int(next(it))
out = []
for _ in range(t):
x = int(next(it))
# compute digit presence of x
dp = [False]*10
tmp = x
while tmp:
dp[tmp%10] = True
tmp //=10
# factorize and get divisors
factors = factorize(x)
divisors = gen_divisors(factors)
cnt = 0
for d in divisors:
# check common digit
dtmp = d
while dtmp:
if dp[dtmp%10]:
cnt += 1
break
dtmp //=10
# note: if d==0? not possible
out.append(str(cnt))
sys.stdout.write("\n".join(out))
if __name__ == "__main__":
solve()
Double-check: For x=10, dp: [True,True,False,...] (0 and 1). divisors: [1,2,5,10]. For 1: dtmp=1 => dp[1]=True => cnt+1 break; for 2: dtmp=2 dp[2] false, dtmp=0? Actually while dtmp: dtmp=2, then dtmp%10=2 false, dtmp//=10=0 => loop ends, no count. For 5 similar; for 10: dtmp=10, dtmp%10=0 -> dp[0] True => cnt+1. total 2.
Works.
Now, we need to ensure that for x=0 (not possible) we don't need.
Now, also note that for x=1, tmp while loop: while tmp: 1>0, dp[1]=True, tmp=0. dp[1]=True. Divisors [1]: d=1, while 1: dp[1] true => count 1. Good.
Now, test a few additional cases manually:
x=2 -> dp[2]=True, divisors [1,2]. 1: no digit 1? Actually dp[1] false? For x=2, dp[2]=True only. So 1: while 1: dp[1] false, loop ends, no count. 2: dp[2] true => count 1. Output 1.
x=11 -> dp[1]=True, divisors [1,11]. 1: dp[1] true => count. 11: while 11: 11%10=1 true => count. So 2.
x=100 -> dp[1]=True, dp[0]=True? Actually digits: 1 and 0 and 0, so dp[1]=True, dp[0]=True. Divisors of 100: factors: 2^2 * 5^2 => divisors: 1,2,4,5,10,20,25,50,100. Count those sharing digit 1 or 0: 1 (digit 1) -> true; 2->false;4->false;5->false;10 (digit 1 and 0) -> true;20 (2,0) has 0 -> true;25 (2,5) -> false;50 (5,0) has 0 -> true;100 (1,0,0) has 1 and 0 -> true. So count: 1,10,20,50,100 = 5. Let's check: also maybe 25? No. So 5. Our code should compute that.
Now, verify: x=100; dp: [True,True,...]. Divisors generation: list all. Check each: 1 -> true; 2 -> false;4->false;5->false;10->true;20->true;25->false;50->true;100->true => count=5. Works.
Now, check x=7: dp[7]=True; divisors [1,7]; 1 false; 7 true =>1.
Now, confirm that for x containing digit 0, divisors like 20 works.
Now, ensure that for divisors like 1000? Not relevant.
Now, think about performance: We call while loop on each divisor to check digits; maximum ~1344 divisors per case, each while loop iterates over number of digits of d (max 10 digits because x ≤ 1e9, so d ≤ x ≤ 1e9, so at most 10 digits). So at most ~13440 digit checks per case, trivial.
Now, also factoring: For each case, we iterate over primes until pp > temp. In worst-case (x is prime near 1e9), we iterate over all primes up to sqrt(x) ~31623. That's 3401 primes. For each prime, we do pp maybe compute? Actually we compute pp each time? We can compute pp before? The condition pp > temp: pp is computed each iteration, but that's cheap. The main cost is modulo for each prime. So 3401 mod operations per case, fine. For composite numbers, we break early after factoring out small primes, and temp becomes 1, so we break out when pp > 1, which is immediate after we process small primes? Actually after factoring out all prime factors, temp becomes 1. Then in the next prime iteration, condition pp > 1 is true (since p>=2, 4>1) so we break. So loop may go until the next prime after the largest factor we found, but temp=1, so pp > 1 true, break early. But if the largest prime factor is small, we might have already passed it? Actually we break when pp > temp. If temp becomes 1, then for the next prime we check, p*p > 1 will be true, so break. So we break right after we finish factoring out all primes, which is when we reach a prime > sqrt(original remaining). So overall number of primes processed is about up to the largest prime factor's sqrt? But anyway <= 3401.
Thus very efficient.
Therefore final solution is ready.
One more thought: When we generate divisors, the order may be arbitrary; but we just count.
Now, note: For x up to 10^9, the number of divisors can be up to 1344, but our divisor generation might produce unsorted list; we don't care.
Now, we need to ensure that for x = 1, the factor dictionary is empty, and gen_divisors returns [1] correctly. Our code: divisors = [1]; then for each factor (none), we skip loop, so remains [1]. Good.
Now, we must ensure that the while loop for digit presence for x=0? Not needed.
Now, finalize.
Potential pitfalls: When x contains digit 0, dp[0] is True. In has_common, we check dtmp%10. For d=10, dtmp%10 = 0, dp[0] True, works. For d=0? not possible.
Now, what about d like 100? dtmp=100 -> dtmp%10=0 -> true.
Thus correct.
Now, we will produce the answer accordingly.
But the problem statement says: "You have to find the no. of positive integers d, such that d is the divisor of x, and x and d have at least one common (the same) digit in their decimal representations." That's exactly.
Now, sample output matches.
Now, we can finalize the solution.
I'll include comments.
Now, double-check reading input: using sys.stdin.read to handle multiple lines.
Now, produce final answer.
But wait: There might be a nuance: The problem uses "the same digit" meaning at least one digit that appears in both numbers. That is what we did.
Now, we can consider alternative approach: count divisors that do NOT share any digit, subtract from total number of divisors. But that's just a variation.
Now, final code.
I'll test with some random numbers mentally:
x=24, divisors: 1,2,3,4,6,8,12,24. digits of x: 2 and 4. Which divisors share? 2 (2), 4 (4), 12 (2,1? 12 has digits 1 and 2, shares 2), 24 (2,4) shares both, maybe also? 1 none, 3 none, 6 (6) none, 8 none. So count=4. Our code: dp[2]=True, dp[4]=True. For each divisor: 1->false;2->true;3->false;4->true;6->false;8->false;12->true;24->true => 4. Good.
Now, x=111, digits {1}. Divisors of 111 = 3 * 37? Actually 111=3*37. Divisors:1,3,37,111. All except 3 and 37? Check: 1 shares 1? digit 1 -> yes; 3 -> digit 3 no; 37 -> digits 3 and 7 no; 111 -> digits 1,1,1 -> yes. So count=2. Our code: dp[1]=True. 1->true,3->false,37->false,111->true =>2.
Now, x=101010, digits 1,0. Many divisors may share 0 or 1. Our code should handle.
Now, the only tricky part is the digit 0: We used while tmp>0 to set dp[0]. However, what if x itself contains digit 0? Then we set dp[0]=True. That works because while tmp>0 will not handle the case when x is 0, but x>=1. So fine.
Now, note that for numbers like 1000, while tmp>0 will eventually set dp[0] because we get remainder 0 from the least significant digits: e.g., 1000%10 = 0, set dp[0]=True; then tmp=100; 100%10=0, again set True; then tmp=10; 10%10=0; then tmp=1; 1%10=1; then tmp=0. So dp[0] gets set. Good.
Now, final answer.
Now, maybe we can further optimize by early break in has_common: we already break on true.
Now, we should also consider if the divisor generation can be done iteratively over i from 1 to sqrt(x). As discussed, that might be simpler to code and avoid prime sieve. Given that T=100, sqrt=31623, 3.16 million loops is fine. But the factoring approach is also simple and perhaps more educational. However, I think both are acceptable. I'll keep the factoring approach because it's efficient and demonstrates number theory.
But there's one potential issue: The divisor generation function above might produce duplicates if we are not careful? Actually it produces each divisor exactly once because each divisor is represented uniquely by exponent choices. So fine.
Now, finalize code.
Now, I'll provide the solution with explanation.
I'll also consider if there is any case where the factor dictionary contains a composite number from the leftover temp after trial division? For n ≤ 1e9, if after dividing by primes up to sqrt(original n), if temp > 1, then temp is either prime or possibly product of two primes both > sqrt(n)? That can't happen because if both > sqrt(n), product would exceed n. So temp must be prime. So we add as prime factor. Good.
Now, verify that for x=1, after loop, temp=1, so we don't add anything. factors = {}.
Now, note: In Python, the modulo operation on large numbers is okay.
Now, we need to be careful that while factoring we might get a prime factor p that is larger than 31623. For example, x=999999937 (a prime near 1e9). After trial division with all primes up to 31623, none divide, so temp remains = x. Then we break out of loop because pp > temp will eventually be true when p exceeds sqrt(temp)? Actually condition is if p*p > temp: break. Since we iterate over primes, at some point p becomes > sqrt(temp). For example, temp = 999999937, sqrt ≈ 31622. So the largest prime less than or equal to 31622 is 31607? Actually there are primes up to 31607 maybe. At the point where p=31607, pp ≈ 999,000,000 < temp? Actually 31607^2 = 998, maybe 999 million? Let's compute: 31607^2 = (3160731607) =? 31600^2=998560000, plus something, maybe 998, something. Actually 31607^2 = 3160731607. 31600^2=998,560,000, plus 2316007=442,400, plus 49 = 999,002,449? That might be > 999,999,937? Wait 31623^2 = 1,000,014,129, so 31607^2 is less than that. But we need to check when pp > temp. For temp=999,999,937, sqrt ≈ 31622.7. So primes up to 31607 have pp less than temp? 31607^2 =? Let's compute exactly: 31607^2 = (31000+607)^2 = 961000000 + 231000607= 37,634,000? Actually 231000607 = 37,634,000; plus 607^2=368,449; sum = 961,000,000+37,634,000=998,634,000; +368,449=999,002,449. That's less than 999,999,937. So pp < temp. So condition fails, we continue to next prime. Next prime after 31607 is 31627? Actually primes list up to 31623, but we limited primes to up to 31623. In our sieve, we generated primes up to 31623 inclusive. So the largest prime in our list is ≤31623. 31627 > 31623, so not in list. So we have primes up to 31623. Check p=31627 not included. So we will iterate over all primes in PRIMES, which ends at maybe 31607 or 31627? Actually 31627 is >31623, so not included. The last prime ≤31623 is? 31601? 31607? 31627 >31623, so the last prime in list is 31607? But 31607^2 = 999,002,449 < 999,999,937, so pp > temp condition won't be true until we finish the loop. But after the last prime, we exit the for loop because there are no more primes. However, we need to break out when pp > temp. In the for loop, we iterate over all primes. For each prime p, we check if p*p > temp: break. So after processing p=31607, next p might be the next prime in the list, which would be 31627? Actually there is no such because our list only goes up to 31623, so the next prime after 31607 within 31623 is? 31607, next prime 31627 >31623, not in list. So the loop ends after finishing all primes. But we haven't broken early because for all primes in our list, pp <= temp (since the largest prime in list is less than sqrt(temp)? Let's compute sqrt(temp) ~31622.7. The largest prime ≤31623 is? 31627 >31623, so the largest prime ≤31623 is 31607? Actually 31607 < 31623, next prime 31627 > 31623. So 31607 is the largest prime in our list if we generate up to 31623. But 31607^2 = 999,002,449 which is less than temp. So for all primes in list, pp > temp never becomes true. Thus we will not break early; we will exhaust the entire primes list. That's fine; we will check modulo for each prime up to 31607 (about 3400). Then after the loop, we have temp still = x (since none divided). Then we check if temp > 1, and add as factor. So factorization is correct. The code doesn't rely on early break; it's fine. The loop will iterate all primes, but that's okay.
But we could potentially break early if we add condition: if p*p > temp: break; that would be true when we reach a prime greater than sqrt(temp). However, since our prime list might not contain a prime > sqrt(temp) if the largest prime in list is less than sqrt(temp). For numbers where temp remains > sqrt(original) after some divisions? Actually if temp is large and sqrt(temp) is about 31622, and our list's maximum prime is 31607 (if 31607 is prime) which is slightly less than sqrt(temp), then we will not break; we'll exhaust the list. But we'll still do ~3400 iterations, which is fine. If we want to break exactly when p > sqrt(temp), we could compute sqrt_temp and break when p > sqrt_temp. But it's unnecessary.
So factorization is fine.
Now, we have to consider that the prime list includes up to 31623 inclusive. But we said the limit is 31623, which includes 31607 and maybe 31627? Actually 31627 > 31623, so not included. The largest prime ≤31623 is 31601? Let's compute: 31601 is prime? Possibly. 31607 is also prime? 31607 = 31607, maybe prime. 31627 is >31623, so not. So the max prime is 31607 or 31601 or maybe 31627? Actually 31627 is 31627, but 31627 > 31623, so not. So we have primes up to 31607. That's fine; we will check all primes up to 31607. That covers all possible prime factors ≤31607. For a composite factor ≤ sqrt(x) but >31607? That can't happen because sqrt(x) ≤ 31623, and any prime factor ≤ sqrt(x) would be ≤ 31623. But 31607 is the largest prime ≤31623. However, there could be composite factors whose smallest prime factor is ≤ sqrt(x). But we factor by primes, so if the smallest prime factor is >31607, then the number would be prime because any composite number has a factor ≤ sqrt(n). If the smallest prime factor is >31607, then sqrt(n) must be at least that prime, but n would be at least p^2 > (31607)^2 ≈ 999 million. Actually n could be a product of two primes both >31607, then each >31607, but their product would be > (31607)^2 > 10^9? Actually (31607)^2 = 999,002,449 < 10^9, but if both primes >31607, say 31627 and 31657, product ≈ 1,001, something, > 1e9? 3162731657 ≈? 3162731657 = (31642^2 -15^2) approx 1,001,? Actually 31642^2 ≈ 1,001,? Let's compute: 31640^2 = 1,001,089,600, so it's likely above 1e9. But it could be a number like 31607 * 31627 ≈ 999,002,449 +? Actually 3160731627 = 31607(31607+20) = 31607^2 + 2031607 = 999,002,449 + 632,140 = 999,634,589 < 1e9. So a composite number with both factors >31607 is possible? The smallest factor is >31607? Actually both factors >31607 means the smallest factor is >31607. For example, 31627 (which is 31627) and 31657? Their product >1e9. But 3162731607? The smallest factor is 31607, which is ≤31607. So if the smallest prime factor >31607, it must be at least 31627. But if the number is composite with two prime factors both >31607, then the smallest is >31607, but the product would be > (31627)^2? (31627)^2 =? 31627^2 = (31600+27)^2 = 998,560,000 + 23160027=1,706,400 + 27^2=729 => total = 1,000,267,129? Actually 998,560,000+1,706,400=1,000,266,400+729=1,000,267,129 >1e9. So any product of two primes both >31607 is > 1e9. Therefore, for numbers ≤1e9, any composite number has a prime factor ≤ sqrt(n) ≤ 31623, and that prime factor is ≤31623, which is within our prime list (since we have all primes up to 31623). However, if the prime factor is exactly 31627? But 31627 >31623, so that can't be ≤ sqrt(n) because sqrt(n) ≤31623. So prime factor cannot be >31623. So our prime list up to 31623 covers all possible prime factors. So it's safe.
But we only generated primes up to 31623, which includes primes up to 31607 but not 31627. Since sqrt(1e9) is about 31622.77, any prime factor ≤ sqrt(n) must be ≤ 31622. So the largest possible prime factor ≤ sqrt is at most 31607? Actually the largest prime ≤31622 is? 31601? 31607? 31627 is >31622, so not. So our prime list must include all primes up to 31622. We set limit = 31623, so primes up to 31623 includes all numbers ≤31623. But 31623 is not prime (it's 3*10541?). So the largest prime ≤31623 is indeed 31607? Let's check: 31607, 31601, 31627 is >31623. So our list includes all primes ≤31623, which includes all primes ≤31622. So it's sufficient.
But wait, is 31607 the largest prime ≤31623? Could there be 31613? 31613 maybe? 31613 =? Let's quickly list primes around that: I recall primes: 31601, 31607, 31627, 31643... I think 31607 is prime, 31613 maybe not. I'm not certain. But anyway, the sieve up to 31623 will capture all primes up to that, so we are fine.
Thus factoring works.
Now, note: When we generate divisors, we multiply numbers; they can become large (up to 10^9). Python int handles.
Now, we must ensure we don't miss divisor 1. Already included.
Now, finalize.
I'll produce final answer with code and explanation.
Now, there is a small nuance: In the problem statement, they may require counting divisor d such that d and x have at least one common digit. If x contains digit 0, then any divisor that has digit 0 qualifies. That includes numbers like 10, 20, etc. Our check for digit 0 works because while loop on d will see 0 digits only if d is a multiple of 10? Actually numbers like 101 contain digit 0? Yes 101 has 0 in the middle? Actually 101 digits: 1,0,1; our while loop processes digits from least significant: 101%10=1 (check dp[1]), then //10=10; then 10%10=0 (check dp[0]), so catches. So any number containing 0 anywhere is caught.
Now, also note that for numbers like 1000000, while loop will iterate many times but okay.
Now, finalize.
But before finalizing, I'll think about potential memory or time issues: The PRIMES list has about 3401 elements. The sieve up to 31623 is quick.
Now, the code: In solve(), we read all input, for each x we compute dp, factorize, generate divisors, count. That's fine.
One minor improvement: We could precompute digit sets for divisors on the fly without generating full list if we want, but not needed.
Now, edge case: x=10^9 = 1000000000. Digit set: {1,0}. Factors: 2^9 * 5^9. Divisors count 100. Our gen_divisors: for p=2 exp=9 and p=5 exp=9. We'll generate 100 divisors. Then check each. Works.
Now, verify that our divisor generation method does not produce duplicates: For two primes, we multiply properly.
Now, test with x=10^9. Code:
-
dp: while tmp: 1000000000 %10 = 0 => dp[0]=True, tmp=100000000; 100000000%10=0 set, tmp=10000000; ... eventually tmp becomes 1 then 1%10=1 set dp[1]=True, tmp=0. So dp[0] and dp[1] true.
-
factors: factorize(1000000000): For p=2, while dividing: count 9; temp becomes 1953125? Actually 1000000000 / 2^9 = 1000000000/512 = 1953125? Let's compute: 2^9=512, 1000000000/512=1953125 exactly? 1953125512 = 1953125500=976,562,500 + 1953125*12=23,437,500 = 1,000,000,000. Yes. Then for p=5: check 5 divides 1953125, count exp=9? 5^9 = 1953125? Actually 5^9 = 1953125 exactly. So after dividing, temp becomes 1. So factors: {2:9, 5:9}.
-
gen_divisors: start with [1]. For p=2, exp=9: new list: for e from 0 to 9: mul = 1,2,4,8,...512; for each existing divisor (initially [1]), add d*mul => produces [1,2,4,8,16,32,64,128,256,512]. Then for p=5, exp=9: for each divisor in that list (10 numbers), multiply by 5^0..5^9. This yields 100 divisors. Then we check each. Works.
Now, output: We'll count how many of these contain digit 0 or 1. Many will contain 0? For example, 2^a * 5^b yields numbers that are powers of 2 or 5 or combinations. Powers of 2: 1,2,4,8,16,32,64,128,256,512,... none contain 0? 16 doesn't; 32; 64; 128; 256; 512; 1024? Actually 1024 is not a divisor of 10^9? 1024 = 2^10, but we only have up to 2^9=512. So powers of 2 up to 512 have digits {1,2,4,5,6,8}? 512 has digits 5,1,2; no 0. Powers of 5: 5,25,125,625,3125,15625,78125,390625,1953125. Some contain 0? 5: no; 25: no; 125: no; 625: no; 3125: digits 3,1,2,5; no; 15625: digits 1,5,6,2,5; no; 78125: 7,8,1,2,5; no; 390625: digits 3,9,0,6,2,5 -> contains 0! So 390625 qualifies. Also 1953125: digits 1,9,5,3,1,2,5 -> no 0. Also combinations like 10 = 2*5: digits 1,0 -> qualifies. Many others will contain 0 when they have factor 2^a * 5^b such that the decimal representation includes a 0. Could be many. Our code will count them. So answer is computed.
Now, ensure we handle the possibility of x being 0? No.
Now, potential pitfalls: In the factorization function, we used PRIMES list which is precomputed. However, if x is 1, we skip loop, factors empty, then return {}. That's fine.
Now, for x like 10^9, after factorizing, the leftover temp becomes 1, so fine.
Now, we should also consider x being a perfect square like 36: divisors: 1,2,3,4,6,9,12,18,36. Digit set: {3,6}. Count: 1? 1 no; 2 no; 3 yes; 4 no; 6 yes; 9 no; 12 (digits 1,2) no; 18 (1,8) no; 36 (3,6) yes => 3 (3,6,36). Our code should compute.
Now, test with code quickly mentally: dp[3]=True, dp[6]=True. divisors: ... check each.
Works.
Now, done.
Now, we must also consider that the number of test cases T can be up to 100. Our code will process each independently.
Now, final output.
Now, we can write solution explanation.
But the problem may be from some contest that expects an efficient solution. This is fine.
Now, final answer.
Let's produce final solution code with comments.
We'll also include a faster digit checking function using boolean list.
Now, I'll craft the final answer. ```python
import sys
------------------------------------------------------------
Precompute all primes up to sqrt(10^9) ≈ 31623
------------------------------------------------------------
def sieve(limit: int):
is_prime = [True] * (limit + 1)
is_prime[0] = is_prime[1] = False
for i in range(2, int(limit ** 0.5) + 1):
if is_prime[i]:
for j in range(i * i, limit + 1, i):
is_prime[j] = False
return [i for i, v in enumerate(is_prime) if v]
PRIMES = sieve(31623)
------------------------------------------------------------
Factorize n (n ≤ 10^9) using the pre‑computed primes
------------------------------------------------------------
def factorize(n: int):
factors = {}
temp = n
for p in PRIMES:
if p * p > temp:
break
if temp % p == 0:
cnt = 0
while temp % p == 0:
temp //= p
cnt += 1
factors[p] = cnt
if temp > 1: # remaining prime factor
factors[temp] = 1
return factors
------------------------------------------------------------
Generate all divisors from the prime factorisation
------------------------------------------------------------
def gen_divisors(factors):
divisors = [1]
for p, exp in factors.items():
new_divs = []
mul = 1
for _ in range(exp + 1):
for d in divisors:
new_divs.append(d * mul)
mul *= p
divisors = new_divs
return divisors
------------------------------------------------------------
Main solving routine
------------------------------------------------------------
def solve() -> None:
data = sys.stdin.read().strip().split()
if not data:
return
it = iter(data)
t = int(next(it))
out_lines = []
for _ in range(t):
x = int(next(it))
# ---- digit presence of x ----
digit_present = [False] * 10
tmp = x
while tmp:
digit_present[tmp % 10] = True
tmp //= 10
# ---- factorisation and divisor enumeration ----
factors = factorize(x)
divisors = gen_divisors(factors)
# ---- count divisors sharing at least one digit with x ----
cnt = 0
for d in divisors:
dtmp = d
while dtmp:
if digit_present[dtmp % 10]:
cnt += 1
break
dtmp //= 10
out_lines.append(str(cnt))
sys.stdout.write("\n".join(out_lines))
if name == "main":
solve()