Home > Net >  How to find the first prime number in range on JS
How to find the first prime number in range on JS

Time:03-17

I have this code that finds all the prime numbers between 2 values, but how do i change it to find only the first one?

e.g. 33 and 147 = 37

let a, b, i, j, primo;

a = window.prompt("Numero minimo: ");

b = window.prompt("Numero maximo: ");

console.log("Numeros primos entre "   a   " e "   b << " é: ");


for (i = a; i <= b; i  ) {
    if (i == 1 || i == 0)
        continue;


    primo = 1;

    for (j = 2; j < i;   j) {
        if (i % j == 0) {
            primo = 0;
            break;
        }
    }


    if (primo == 1)
        document.write(i," ");
}

CodePudding user response:

You can extend the final if statement with this:

  if (primo == 1) {
    document.write(i, " ");
    break;
  }

break allows you to exit the for loop. You can learn more here: https://www.w3schools.com/js/js_break.asp

let a, b, i, j, primo;

a = window.prompt("Numero minimo: ");

b = window.prompt("Numero maximo: ");

console.log("Numeros primos entre "   a   " e "   b << " é: ");


for (i = a; i <= b; i  ) {
  if (i == 1 || i == 0)
    continue;


  primo = 1;

  for (j = 2; j < i;   j) {
    if (i % j == 0) {
      primo = 0;
      break;
    }
  }


  if (primo == 1) {
    document.write(i, " ");
    break;
  }
}

CodePudding user response:

That would be the algorithm for find the first prime in a array.

function makeArr(start, end) {
  end  
    return Array.from({length: (end-start)}, (v, k) => k start)  
}
 
isPrime = num => {
    for(let i = 2, s = Math.sqrt(num); i <= s; i  )
        if(num % i === 0) return false; 
    return num > 1;
}

nums = makeArr(33,147);
r = nums.filter(n => isPrime(n))
console.log(r[0])

Wrapped in a function example

function getFirstPrimeNumber(s, e) {
  const start = parseInt(s);
  let end = parseInt(e);
  end  ;
  const _a= Array.from({length: (end-start)}, (v, k) => k start)
  const isPrime = num => {
  for(let i = 2, s = Math.sqrt(num); i <= s; i  )
      if(num % i === 0) return false; 
  return num > 1;
  }
  const primes = _a.filter(n => isPrime(n));
  return primes[0];
}


const a = window.prompt("Numero minimo: ");
const b = window.prompt("Numero maximo: ");
const r = getFirstPrimeNumber(a,b)
console.log('result', r);

  • Related