Skip to content

Instantly share code, notes, and snippets.

@camark
Created April 28, 2016 02:13
Show Gist options
  • Select an option

  • Save camark/f308eb12296c4ac9845540f625b2c88c to your computer and use it in GitHub Desktop.

Select an option

Save camark/f308eb12296c4ac9845540f625b2c88c to your computer and use it in GitHub Desktop.
求一个数组里面的素数
'use strict'
function getPrimes(arr){
return arr.filter(function(x){
if(x<2) {
return false
}
for(var i=2;i<=parseInt(x/2);i++){
if(x%i==0) return false;
}
return true
})
}
// 测试:
var
x,
r,
arr = [];
for (x = 1; x < 100; x++) {
arr.push(x);
}
r = get_primes(arr);
if (r.toString() === [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97].toString()) {
alert('测试通过!');
} else {
alert('测试失败: ' + r.toString());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment