function primes(upto, func){
if( upto > 25000 ){ return large_primes(upto, func); }
upto -= 1;
var flags = new Array(upto);
for( i = 0; i < upto; i++){ flags[i] = true; }
for( i = 0; i < upto; i++){
if( flags[i] ){
var prime = i + 2;
var k = i + prime;
while( k < upto ){
flags[k] = false;
k += prime;
}
func(prime);
}
}
}
function large_primes(upto, func){
// The Algorithm is adapted from http://w...content-available-to-author-only...k.com/~jrm/printprimes.html
// This code is a translated version of Andreas Raab's #largePrimesUpTo:do: method
// which was written for the Squeak Smalltalk environment.
var idx_limit = Math.floor(Math.sqrt(upto)) + 1;
var flags = new Array(Math.floor((upto + 2309) / 2310) * 60 + 60);
for( i = 0; i < flags.length; i++){ flags[i] = 0xFF; }
var primes_up_to_2310 = [];
primes(2310, function(p){ primes_up_to_2310.push(p); });
var mask_bit_idx = new Array(2310);
mask_bit_idx[0] = 0;
mask_bit_idx[1] = 1;
var bit_idx = 1;
for( i = 0; i < 5; i++ ){ func(primes_up_to_2310[i]); }
var idx = 5;
for( n = 2; n < 2310; n++ ){
while( primes_up_to_2310[idx] < n ){ idx += 1; }
if( n == primes_up_to_2310[idx] ){
mask_bit_idx[n] = bit_idx += 1;
} else if( n % 2 === 0 || n % 3 === 0 || n % 5 === 0 || n % 7 === 0 || n % 11 === 0 ){
mask_bit_idx[n] = 0;
} else {
mask_bit_idx[n] = bit_idx += 1;
}
}
for( n = 13; n <= upto; n += 2 ){
if( mask_bit = mask_bit_idx[n % 2310] ){
byte_idx = Math.floor(n / 2310) * 60 + (mask_bit-1 >> 3);
bit_idx = 1 << (mask_bit & 7);
if( flags[byte_idx] & bit_idx ){
func(n);
if( n < idx_limit ){
idx = n * n;
if( !(idx & 1) ){ idx += n; }
while( idx <= upto ){
if( mask_bit = mask_bit_idx[idx % 2310] ){
byte_idx = Math.floor(idx / 2310) * 60 + (mask_bit-1 >> 3);
mask_bit = 255 - (1 << (mask_bit & 7));
flags[byte_idx] = flags[byte_idx] & mask_bit;
}
idx += 2 * n;
}
}
}
}
}
}
var limit = 100000;
// var limit = Math.pow(2,30);
try{
if( process.argv.length == 3 ){ limit = parseInt(process.argv[2],10); }
} catch(e){}
max = 0;
primes(limit, function(p){
s = String(p);
if(s == s.split("").reverse().join("")) { max = p; }
});
try{ console.log(max) } catch(e){ print(max); }