import sympy

factor_master_list = [[],[1],[1,2],[1,3],[1,2,4],[1,5],[1,2,3,6],[1,7],[1,2,4,8],[1,3,9]]

all_list = []

#first do inc -> dec
for start_digit in range(1,9): #cant start with 0 or 9
    for max_digit in range(start_digit+1,10): #go up
        for end_digit in range(0,max_digit): #go down
            for inc in factor_master_list[max_digit-start_digit]:
                for dec in factor_master_list[max_digit-end_digit]:
                    if inc > 1 or dec > 1: #cant both be 1 or angle is 90 degrees
                        first_half = list(range(start_digit,max_digit,inc)) #this misses the max digit but its picked up below
                        second_half = list(range(max_digit,end_digit-1,-1*dec))
                        num = ""
                        for i in first_half:
                            num += str(i)
                        for i in second_half:
                            num += str(i)
                        all_list.append(int(num))

#then do dec -> inc
for start_digit in range(1,10): #cant start with 0
    for min_digit in range(0,start_digit): #go down
        for end_digit in range(min_digit+1,10): #go up
            for dec in factor_master_list[start_digit-min_digit]:
                for inc in factor_master_list[end_digit-min_digit]:
                    if dec > 1 or inc > 1: #cant both be 1 or angle is 90 degrees
                        first_half = list(range(start_digit,min_digit,-1*dec)) #this misses the min digit but its picked up below
                        second_half = list(range(min_digit,end_digit+1,inc))
                        num = ""
                        for i in first_half:
                            num += str(i)
                        for i in second_half:
                            num += str(i)
                        all_list.append(int(num))

all_list.sort()
prime_list = []
for i in all_list:
    if sympy.isprime(i):
        prime_list.append(i)

f = open("b135601.txt", "w")
k = 1
for n in all_list:
    line = str(k) + " " + str(n) + "\n"
    f.write(line)
    k += 1
f.close()

f = open("b167841.txt", "w")
k = 1
for n in prime_list:
    line = str(k) + " " + str(n) + "\n"
    f.write(line)
    k += 1
f.close()