After seeing some sample Google Interview Questions that included this question, I couldn’t resist the challenge…
def bigE() {
BigDecimal e = new BigDecimal(1.0G)
BigDecimal temp = new BigDecimal(1.0G)
for (int i in 1..100) {
temp *= i
e += new BigDecimal("1")
.divide(temp, new java.math.MathContext(10000))
}
return e.toString()
}
def isPrime(long n) {
if (n < 2) return false
if (n == 2 || n == 3) return true
if (n%2 == 0 || n%3 == 0) return false
long sqrtN = (long)Math.sqrt(n)+1
for (long i=6L; i < sqrtN; i += 6) {
if (n%(i-1) == 0 || n%(i+1) == 0) return false
}
return true
}
def firstPrimeBySize(n) {
String e = bigE()
for (int i in 2..e.size()-n) {
String chunk = e.substring(i,i+n)
if (isPrime(new BigDecimal(chunk).toLong())) {
return "$chunk at position $i"
}
}
}
assert firstPrimeBySize(10) == "7427466391 at position 100"