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

JavaScript implementation of finding prime numbers code sharing_javascript skills

WBOY
Release: 2016-05-16 16:07:59
Original
1970 people have browsed it

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;
}

Copy after login

Usage examples:

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

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