# Author: Manfred Scheucher
# Date  : May 25 2015 

from sys import argv
from itertools import combinations

def prime_sieve(x):
	S = str(x).replace('.','')
	#print S

	def substrs(s):
		l = len(s)
		for a,b in combinations(range(l+1),2):
			yield s[a:b]

	p = 1
	while True:
		p = next_prime(p)
		T = [int(s) for s in S.split()]
		T = [t for t in T if t >= p]
		if not T: break

		umin = min(T)
		for t in T:
			if t < p: continue
			for u in substrs(str(t)):
				u=int(u)
				if u < p: continue
				umin = min(umin,u)
				if umin==p: break
			if umin==p: break

		p = next_prime(umin-1)

		S = S.replace(str(p),' ',1)
		
		while '  ' in S: S = S.replace('  ',' ')

	return [int(s) for s in S.split()[:-1]] # last term might be incomplete



def to_file(path,S,offset):
	with open(path,'w') as f:
		for s in S:
			f.write(str(offset)+" "+str(s)+"\n")
			offset+=1


digits = int(argv[1])

x = pi.N(digits=digits)
S = prime_sieve(x)

print "sequence:"
print ", ".join(str(s) for s in S)

path = "b"+str(digits)+".txt"
print "write result to file:",path
to_file(path,S,1)