0

I'm trying to solve this problem where you loop through the numbers between 1 to 60 to find the total prime numbers. Here is what I've come up with:

var totalPrimeNumber = 0;
for(let i=1; i<=60; i++) {
    for(let j= 2; j< i; j++) {
        if(i%j ==0) {
            console.log(i, "is not a prime number");
        }
        console.log(i, "is a prime number");
        totalPrimeNumber+=1;
    }
}

But the output is wrong:

3 is a prime number
4 is not a prime number
4 is a prime number
4 is a prime number
5 is a prime number
5 is a prime number
5 is a prime number
6 is not a prime number
6 is a prime number
6 is not a prime number
6 is a prime number
6 is a prime number
6 is a prime number
7 is a prime number
7 is a prime number
7 is a prime number

Do you know how I can fix this problem?

Snirka
  • 572
  • 1
  • 4
  • 18
An Chi Lê
  • 19
  • 2
  • You need to `break;` out of the loop once you've established that a number is not prime. Also for checking primes, `let j=2; j<=Math.sqrt(i); j++` is sufficient. – Niet the Dark Absol Jun 30 '21 at 09:53
  • A better approach is to write a function `isPrime(number)` that returns a boolean and to call it in the loop for each value of `i`. Split your problems into smaller problems and handle them one at a time. Something like this: https://jsfiddle.net/nha613vg/ –  Jun 30 '21 at 10:07
  • Does this answer your question? [Number prime test in JavaScript](https://stackoverflow.com/questions/40200089/number-prime-test-in-javascript) – ceving Jun 30 '21 at 10:17

2 Answers2

2

You should break the inner loop once you know that the number is not a prime!

You can also improve your code by only checking numbers up to the square-root as divider. E.g. if you check 100 to be a prime, then you only need to check numbers up to 10 since higher numbers will have a lower multiplicator (e.g. you don't need to check 50 since you already checked 2 and 2*50 = 100)

var totalPrimeNumber = 0;
for (let i = 1; i <= 60; i++) {
  let prime = i > 1;
  for (let j = 2; j <= Math.sqrt(i); j++) {
    if (i % j == 0) {
      prime = false;
      break;
    }
  }
  if (prime) {
    console.log(i, "is a prime number");
    totalPrimeNumber += 1;
  } else {
    console.log(i, "is not a prime number");
  }
}
Jamiec
  • 128,537
  • 12
  • 134
  • 188
L. Monty
  • 852
  • 8
  • 17
1

You could also try Array.filter to select only those numbers in an Array that are primes, for example:

function isPrime(n) {
    if (n < 2) {
        return false;
    }
    for(let i = 2; i < n; i++) {
        if(n % i === 0) return false;
    }
    return true;
}

const count = 60;
const numbers = Array.from({ length: count}, (v,k) => k + 1);
const primes = numbers.filter(n => isPrime(n))
console.log("Primes:", primes)
Terry Lennox
  • 24,896
  • 3
  • 23
  • 34