print prime number using user value in js code example
Example 1: javascript find a prime number
function isPrime(num) {
if(num < 2) return false;
for (let k = 2; k < num; k++){
if( num % k == 0){
return false;
}
}
return true;
}
Example 2: javascript find prime number
function test_prime(n){
if (n===1) {
return false;
}else if(n === 2){
return true;
}else{
for(var x = 2; x < n; x++){
if(n % x === 0){
return false;
}
}
return true;
}
}
console.log(test_prime(37));
Example 3: JS print all prime numbers
const lowerNumber = parseInt(prompt('Enter lower number: '));
const higherNumber = parseInt(prompt('Enter higher number: '));
console.log(`The prime numbers between ${lowerNumber} and ${higherNumber} are:`);
for (let i = lowerNumber; i <= higherNumber; i++) {
let flag = 0;
for (let j = 2; j < i; j++) {
if (i % j == 0) {
flag = 1;
break;
}
}
if (i > 1 && flag == 0) {
console.log(i);
}
}