Home  >  Article  >  Web Front-end  >  JavaScript implementation of finding prime numbers code sharing_javascript skills

JavaScript implementation of finding prime numbers code sharing_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:07:591971browse

Okay, there is no background explanation, no advanced skills, just boring, I want to find all the prime numbers within 10,000. So here we go:

function zhishu(num) {
  if (num == 1) {
    return false;
  }
  if (num == 2) {
    return true;
  }
  for (var i = 2; i <= Math.sqrt(num); i++) {
    if (num % i == 0) {
      return false;
    }
  }
  return true;
}

Usage examples:

var zhishuArray = [];
for (var j = 1; j < 100000; j++) {
  if (zhishu(j)) {
    zhishuArray.push(j);
  }
}
console.dir(zhishuArray);

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