1
+ # search pruning for below conditions
2
+ # 1. search set size greater than k
3
+ # 2. sum of search set greater than m
4
+ # 3. sum of current search set plus remaining all '9' numbers still less than m
5
+
6
+ def search (s , k , m , results ):
7
+ sum_s = sum (s )
8
+ if (len (s ) > k or sum_s > m or sum_s + (k - len (s )) * 9 < m ): return
9
+ if len (s ) == k and sum_s == m :
10
+ results .append (int ("" .join (map (str , s ))))
11
+ return
12
+
13
+ start = 1 if len (s ) == 0 else 0
14
+ for i in range (start , 10 ):
15
+ s .append (i )
16
+ search (s , k , m , results )
17
+ s .pop (- 1 )
18
+
19
+ def gcd (a , b ):
20
+ if b == 0 : return a
21
+ else : return b if a % b == 0 else gcd (b , a % b )
22
+
23
+ def is_prime (n ):
24
+ lo = 2
25
+ hi = int (n ** 0.5 )+ 1
26
+ for i in range (lo , hi ):
27
+ if n % i == 0 : return False
28
+ return True
29
+
30
+ n = int (input ())
31
+ for i in range (n ):
32
+ k , m = map (int , input ().split ())
33
+ results = []
34
+ search ([], k , m , results )
35
+ print ("Case %d" % (i + 1 ))
36
+ ans = []
37
+ is_ok = False
38
+ for r in results :
39
+ m1 = sum (map (int , list (str (r + 1 ))))
40
+ g = gcd (m , m1 )
41
+ if g > 2 and is_prime (g ):
42
+ is_ok = True
43
+ ans .append ((m1 , r ))
44
+
45
+ if not is_ok :
46
+ print ("No Solution" )
47
+ else :
48
+ ans .sort (key = lambda x :(x [0 ], x [1 ]))
49
+ print ("\n " .join (map (lambda x : "%d %d" % (x [0 ], x [1 ]), ans )))
0 commit comments