Ejemplo 1: javascript encuentra un número primo
// This seems to be the most common and comprehensive means
// of implementing a 'is a number a prime function' in javascript
// if you would like t0 learn more complex , but efficient algorithms.
// Visit the link below
// https://stackoverflow.com/questions/11966520/how-to-find-prime-numbers-between-0-100
function isPrime(num) {
if(num < 2) return false;
for (let k = 2; k < num; k++){
if( num % k == 0){
return false;
}
}
return true;
}
Ejemplo 2: JS imprime todos los números primos
// program to print prime numbers between the two numbers
// take input from the user
const lowerNumber = parseInt(prompt('Enter lower number: '));
const higherNumber = parseInt(prompt('Enter higher number: '));
console.log(`The prime numbers between ${lowerNumber} and ${higherNumber} are:`);
// looping from lowerNumber to higherNumber
for (let i = lowerNumber; i <= higherNumber; i++) {
let flag = 0;
// looping through 2 to user input number
for (let j = 2; j < i; j++) {
if (i % j == 0) {
flag = 1;
break;
}
}
// if number greater than 1 and not divisible by other numbers
if (i > 1 && flag == 0) {
console.log(i);
}
}
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)