How is it not dodging 2 and 3?

I want to know how the below code is not dodging 2 and 3. When the isPrime() loop will start, won’t 2%2 give 0 and return false??? Unable to understand the algo here :frowning:

  **Your code so far**

function sumPrimes(num) {
  // Helper function to check primality
  function isPrime(num) {
    for (let i = 2; i <= Math.sqrt(num); i++) {
      if (num % i == 0)
        return false;
    }
    return true;
  }

  // Check all numbers for primality
  let sum = 0;
  for (let i = 2; i <= num; i++) {
    if (isPrime(i))
      sum += i;
  }
  return sum;
}

What is the decimal value of sqrt(2)? The function isPrime() goes from 2 until sqrt(num), so if you are checking if 2 is prime, the loop checks all values inbetween 2 and _____. How many values are in that range?

1 Like

It’s because i <= Math.sqrt(num) this condition is not getting fulfilled?

Right, sqrt(2) is roughly 1.414.... and there is no number starting at 2 that is less than 1.414....

1 Like

Plz point out my mistake in this code :

let arr = [];
let n = 22;
for(let i = 1; i <= n; i++){
    if(prime(i)){
        arr.push(i);
    }
} console.log(arr);
function prime(num) {
    if(num === 1 || num === 0){
        return false;
    }
    
    for(let i = 2; i <= Math.floor(Math.sqrt(num)); i++){
        if(num%i == 0){
            return false;
        }return true;
    }
}

It is not returning 2 and 3.

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like
let arr = [];
let n = 22;
// Technically, 1 is not a prime
for (let i = 1; i <= n; i++) {
  if (prime(i)) {
    arr.push(i);
  }
}
console.log(arr);

function prime(num) {
  if (num === 1 || num === 0) {
    return false;
  }
    
  for (let i = 2; i <= Math.floor(Math.sqrt(num)); i++) {
    // === should be used instead of ==
    // but that shouldn't make a change in the output here
    if (num % i == 0) {
      return false;
    }
    // This isn't where you want
    // to return true
    // - a return statement immediately stops your function
    // since this is inside the for loop
    // but the for loop never has any iterations
    // that means you never return true for 2 or 3
    return true;
  }
}
1 Like

Oh my god!!! I can’t believe it I was making such a naive mistake. Thanks a lot sir for your time and patience!!! :slight_smile:

We’ve all been there. I’m happy to help!

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.