Create an algorithm, in JS, to list all primes smaller than or equal to N

Asked

Viewed 1,867 times

-2

I need to create an algorithm in Javascript, to list all prime numbers less than or equal to a given number.

function primeNumber (num){
    var num = 0;
    for (var i = 0; i <= num; i++){
        if ((num % 1 === 0) && (num % num === 0)){
            return (primeNumber(i));
        }
    }
}
console.log(primeNumber(num));

Where am I going wrong?

  • The rest of the division of a number by 1, or the rest of the data by itself, will always be zero. Review the definition of prime number and its algorithm.

2 answers

1


Concept:

To identify a prime number we must divide it successively by prime numbers such as: 2, 3, 5. . . and check whether the division is exact (where the rest is zero) or not exact (where the rest is non-zero).

Simple example in code where the function primeNumbers will interact from 0 to the amount of numbers and the isPrime will check if the same is actually prime number:

function primeNumbers(num) {
  let numbers = new Array();
  for (var i = 0; i <= num; i++) {
    if (isPrime(i)){
      numbers.push(i);
    }
  }
  return numbers;
}
function isPrime(num) {
  for(let i = 2; i <num; i++)
    if(num % i === 0) {
        return false
    };
  return num > 1;
}
console.log(primeNumbers(13));

where the operation will bring all the numbers between the number given.

  • 1

    This program of yours lists odd and not prime numbers.

  • really I’ll arrange @anonimo

  • @anonimo thank you has been arranged now!

0

The most common definition is that "a number is prime if it is divisible by 1 and by itself" or else "it is all the number with two and only two divisors, itself and the unit". So, for example, the number 7 is prime because it is divisible only by 1 and by 7.

  1. By definition the number 2 is a prime number so we must test from the divisor 2.
  2. If in function primeNumber there is some divisor that the rest of the division is equal to 0 he’s not cousin and we can stop with the check.

function primeNumber(num) {
    for (var divisor = 2; divisor < num; divisor++) 
    if (num % divisor == 0) return false;
    return true;
}

var determinadoNumero = 50;

for (var i = 2; i < determinadoNumero; i++) if (primeNumber(i)) console.log(i);

the number 2 is the only prime number that is even.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.