Home >Web Front-end >JS Tutorial >JavaScript Fun Question: Palindromic Prime Numbers
A "palindrome prime" is a number that is itself a prime number, and its palindrome is also another prime number.
For example:
13 17 31 37 71 73
This is a palindromic prime number sequence.
13 is a prime number, and its palindrome 31 is also a prime number.
17 is a prime number, and its palindrome 71 is also a prime number.
The task is as follows:
Find all palindromic prime numbers between two given positive integers. The returned array must be sorted from small to large.
backwardsPrime(2, 100) // => [13, 17, 31, 37, 71, 73, 79, 97] backwardsPrime(9900, 10000) // => [9923, 9931, 9941, 9967]
When we see the word "palindromic prime number", the first thing that comes to mind is a prime number.
Therefore, I guess there must be a way to determine prime numbers:
Number.prototype.isPrime = function(){ var maxFactor = Math.floor(Math.sqrt(this)); for(var i=2;i<=maxFactor;i++){ if(this % i === 0){ return false; } } return true; };
Then, there must be a way to get a palindrome of a certain number:
Number.prototype.palindrome = function(){ return (this + "").split("").reverse().join("") - 0; };
Okay, The materials are all ready, let’s start work!
Traverse from the positive integer on the left to the positive integer on the right. If a number is a prime number and its palindrome is also a prime number, then add it to the array!
However, one thing to note is that if a number is both a prime number and a palindrome itself, that won’t work! Gotta skip it!
Although this seems to be more in line with the literal meaning of "palindrome prime number", the meaning of our question is that two prime numbers are palindromes of each other!
function backwardsPrime(start, stop){ var result = []; for(var i=start;i<=stop;i++){ if(i.isPrime() && i.palindrome().isPrime() && i !== i.palindrome()){ result.push(i); } } return result; }
The above is the content of JavaScript interesting questions: palindromic prime numbers. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!