Created
October 12, 2012 08:12
-
-
Save wangshijun/3877929 to your computer and use it in GitHub Desktop.
javascript: prime number generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var PrimeGenerator = function() { | |
| // 初始化的素数 | |
| this.prime = 1; | |
| // 判断是否是素数 | |
| this.isPrime = function(num) { | |
| var result = true; | |
| if (num !== 2) { | |
| if (num % 2 == 0) { | |
| result = false; | |
| } else { | |
| for (var x = 3, max = Math.sqrt(num); x <= max; x += 2) { | |
| if (num % x == 0) { | |
| result = false; | |
| } | |
| } | |
| } | |
| } | |
| return result; | |
| } | |
| // 查找下1个素数 | |
| this.nextPrime = function() { | |
| this.prime++; | |
| while(!this.isPrime(this.prime)) this.prime++; | |
| return this.prime; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment