# Python 2, 67 bytes f=lambda n,k=0,m=2,p=1:k<n and f(n,k+p*p%m*(`n`in`m`),m+1,p*m)or~-m Test it on [Ideone]. [Ideone]: http://ideone.com/epHD9u