fork download
  1. var BitArray = function(size) {
  2. this.length = size;
  3. this.buffer = new ArrayBuffer(Math.ceil(this.length / 32) * 4);
  4. this.words = new Uint32Array(this.buffer);
  5. };
  6.  
  7. BitArray.prototype.size = function() {
  8. return this.length;
  9. };
  10.  
  11. BitArray.prototype.set = function(bitIndex) {
  12. var wordIndex = Math.floor(bitIndex / 32);
  13. this.words[wordIndex] |= (1 << bitIndex);
  14. };
  15.  
  16. BitArray.prototype.get = function(bitIndex) {
  17. var wordIndex = Math.floor(bitIndex / 32);
  18. return !!(this.words[wordIndex] & (1 << bitIndex));
  19. };
  20.  
  21. function maxPalindromicPrime(bound) {
  22. var sieve_size = (bound - 1) % 6 < 4 ? Math.floor(bound / 6) * 2 + 1 : Math.floor((bound + 1) / 3);
  23. var sieve = new BitArray(sieve_size);
  24. var limit = Math.floor(Math.sqrt(bound));
  25. for(var i = 1;; ++i) {
  26. if(!sieve.get(i)) {
  27. var p = i * 3 + (i & 1) + 1;
  28. if(p > limit) break;
  29. for(var j = p * 2 + i; j < sieve_size; j += p * 2)
  30. sieve.set(j);
  31. for(var j = p * 2 - i - 1; j < sieve_size; j += p * 2)
  32. sieve.set(j);
  33. }
  34. }
  35.  
  36. for(var i = sieve_size - 1; i > 0; --i) {
  37. if(!sieve.get(i)) {
  38. var n = i * 3 + (i & 1) + 1;
  39. if(isPalindrome(n)) {
  40. return n;
  41. }
  42. }
  43. }
  44. }
  45.  
  46. function isPalindrome(n) {
  47. var s = n.toString();
  48. var len = s.length;
  49. for(var i = 0; i < len / 2; ++i) {
  50. if(s[i] != s[len - i - 1]) return false;
  51. }
  52. return true;
  53. }
  54.  
  55. console.log(maxPalindromicPrime(Math.pow(2, 30)));
Runtime error #stdin #stdout #stderr 4.99s 76352KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
/spoj/nodejs_run: line 2: 28950 CPU time limit exceeded node prog.js