get all prime numbers before number javascript code example
Example 1: hwo to make ana array of prime numbers in javascript
function sort_prime(num) {
var prime_num1 = [],
prime_num2 = [];
for (var i = 0; i <= num; i++) {
prime_num2.push(true);
}
for (var i = 2; i <= num; i++) {
if (prime_num2[i]) {
prime_num1.push(i);
for (var j = 1; i * j <= num; j++) {
prime_num2[i * j] = false;
}
}
}
return prime_num1;
}
console.log(sort_prime(5))
Example 2: javascript write all the prime numbers from 1 to 100
function isPrime(num) {
for ( var i = 2; i < num; i++ ) {
if ( num % i === 0 ) {
return false;
}
}
return true;
}
function display(n) {
var arr = [2];
for ( var i = 3; i < n; i+=2 ) {
if ( isPrime(i) ) {
arr.push(i);
}
}
console.log(arr);
}
display(100);
function prime(n,flag) {
( typeof flag === "undefined" || flag === false ) ? flag = false : flag = true;
function isPrime(num) {
if ( num === 0 || num === 1 ) {
return false;
}
for ( var i = 2; i < num; i++ ) {
if ( num % i === 0 ) {
return false;
}
}
return true;
}
if ( flag ) {
var arr = [2];
for ( var i = 3; i <= n; i+=2 ) {
if ( isPrime(i) ) {
arr.push(i);
}
}
return arr;
} else {
return isPrime(n);
}
}