javascript generate prime numbers 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: Prime number function Js
function isPrime(){
const number = parseInt(prompt("Enter a positive number: "));
let isPrime = true;
if (number === 1) {
console.log("1 is neither prime nor composite number.");
}
else if (number > 1) {
for (let i = 2; i < number; i++) {
if (number % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
console.log(`${number} is a prime number`);
} else {
console.log(`${number} is a not prime number`);
}
}
else {
console.log("The number is not a prime number.");
}
}
Example 3: 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))