print prime numbers from 1 to 50 in javascript code example
Example 1: 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);
}
}
Example 2: javascript prime numbers up till a certain number
const sumPrimes = (num) => {
let primes=[];
for (let i = 0; i <= num; i++) {
let flag = 0;
for (let j = 2; j < i; j++) {
if (i % j == 0) {
flag = 1;
break;
}
}
if (i > 1 && flag == 0) {
primes.push(i);
}
}
return primes;
}
console.log(sumPrimes(10))