Home  >  Article  >  Web Front-end  >  Fun JavaScript question: Difference between prime numbers

Fun JavaScript question: Difference between prime numbers

黄舟
黄舟Original
2017-02-04 15:09:441298browse

Prime numbers are not regularly distributed, which can be reflected from the difference between two adjacent prime numbers.
The difference between 2 and 3 is 1, the difference between 3 and 5 is 2, the difference between 5 and 7 is indeed 2, but the difference between 7 and 11 is 4.
At first glance, you really can’t find the pattern, and this is also true.
Between 2 and 50, we can find the following adjacent pairs of prime numbers with a difference of 2:
3-5, 5-7, 11-13, 17-19, 29-31, 41- 43
Obviously, the first pair of prime numbers that satisfies the above conditions is 3-5.
So, in a more general case, what is the first pair of adjacent prime numbers with a gap of g between m and n?
The function prototype is as follows:
gap(g, m, n)

The example is as follows:

gap(2, 5, 7) // --> [5, 7]  
gap(4, 130, 200) // --> [163, 167]  
gap(2, 5, 5) // --> null

Please note that it must be the first pair that meets the g difference adjacent prime numbers.
If not found, return null.
For this type of questions dealing with prime numbers, we all inevitably have to introduce a function to determine prime numbers. Sometimes I can't help but wonder, how cool it would be if this function could be included in the ECMA standard!
However, considering the versatility, the application scenario of this isPrime method is indeed a bit narrow, and it is not suitable to be bound to Number.prototype, so I can only take it off and paste it when doing the questions again and again, sweat^_^.
This question itself is not difficult. In a loop, it will return when it encounters a qualified pair of prime numbers. If there is no qualified pair of prime numbers, it will return null. That's it!

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;    
};    
  
function gap(g, m, n) {  
    var firstPrime;  
    var secondPrime;  
    for(var i=m;i<=n;i++){  
        if(i.isPrime()){  
            firstPrime = secondPrime;  
            secondPrime = i;  
            if(secondPrime - firstPrime === g){  
                return [firstPrime,secondPrime];  
            }   
        }  
    }  
    return null;  
}

The above is the interesting JavaScript question: the difference between prime numbers. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
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