Home > Web Front-end > JS Tutorial > body text

JavaScript Fun Question: Palindromic Prime Numbers

黄舟
Release: 2017-02-04 15:35:50
Original
1784 people have browsed it

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]
Copy after login

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;  
};
Copy after login

Then, there must be a way to get a palindrome of a certain number:

Number.prototype.palindrome = function(){  
    return (this + "").split("").reverse().join("") - 0;  
};
Copy after login

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;  
}
Copy after login

The above is the content of JavaScript interesting questions: palindromic prime numbers. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!