/* PARI program for https://oeis.org/A333085 - © March 2020 by M. F. Hasler
*
* "optional args" (or rather local variables): d = list of digits; U = already used terms relevant for future;
* F = {(positions, digits)}: predictions/requirements concerning future terms;
* P = {positions*10+digits}: possible / proposed terms, corresponding to past digits not yet "described".
*/
A333085_vec(N, d=[], U=[], F=[],P=[], p,dp)={vector(N, i, /* gettime(); /*for debugging: see end of loop*/
for( i=1,oo, /* run over elements of P, then larger primes */
if( i > #P, /* if not an element of P */
i == #P+1 && /* initialize: */ p=10*#d+10;/*if terms referring to past digits are possible they're in P*/
/* adjust first digit if necessary (can safely be omitted since done below) */
F && F[1][1] == #d+1 && F[1][2]*10^logint(p,10)>p && p=F[1][2]*10^logint(p,10);
/* check whether not yet used & self-consistent */
while( setsearch( U, p=nextprime(p+1)) || (p\10-#d < logint(p,10)+2 && digits(p)[p\10-#d] != p%10),)
, p=P[i] );
dp=Vecsmall(digits(p)); /* Now check compatibility with earlier "predictions": */
for( k=1, #F, F[k][1] > #d + #dp && break; F[k][2] == dp[ F[k][1]-#d ] && next;
i > #P && F[k][1] < #d+#dp && p += max(F[k][2]-dp[F[k][1]-#d],1)*(dp=10^( #d+#dp-F[k][1] ))-p%dp /* increment incorrect digit, if not in last place (-> nextprime(p+1)!) */; next(2));
break);
P=setunion(P, select( isprime, vector( #dp,k, 10*(k+#d)+dp[k] ))); /* further terms from new digits */
d=concat(d, dp);
while( F && F[1][1]<=#d, F=F[^1]); /*clean up (no more "future") restrictions */
p\10>#d && F=setunion(F, [divrem(p,10)]); /*add new*/
U=setunion( U, primes( [p\10,p\10+1]*10 )); /*same and contradicting terms are forbidden*/
P=setminus(P, U);
P && U && until( U[1] > P[1] || !U=U[^1],); /* forget used terms < smallest suggestion */
/* if( 100 < t=gettime(), printf("%d, ",[i,p,t])); /* debugging: print terms which require > .1sec */
/* p>=m && printf("a(%d) = %d, ",i,m=p); /* verbose output: print records, using global var m */
p) /*+print([F,P,U])/*debug: print active constraints, suggestions & forbidden terms after a(N)*/}