skip to Main Content

I am trying to find the prime numbers from 1-n (say n=100). Without using built in functions. I have thought about it, and I am not sure how to find them. I tried using two for loops and a count variable to know the count of prime numbers between 1-n. And I also want print these numbers on console.


function countPrimes(num){
  let count=0
  let primeCount=0;
  let i,j
  for(j=2;j<=num;j++)
  {
  for( i=2;i<=j;i++)
  {
    if(j%i==0)
    count++
  }

  if(count==2){
    primeCount++;
  }
  count=0



  }
  return primeCount;
}

console.log(countPrimes(100));


I try to run the above code but getting nothing in the console.

2

Answers


  1. Try to use this code:

    function countPrimes(num){
      let count = 0;
      for(let i = 2; i <= num; i++){
        let isPrime = true;
        for(let j = 2; j < i; j++){
          if(i % j == 0){
            isPrime = false;
            break;
          }
        }
        if(isPrime){
          count++;
          console.log(i);
        }
      }
      return count;
    }
    
    console.log(countPrimes(100));
    
    Login or Signup to reply.
  2. Every number is divided by 1 so we will start i loop from 2

    function countPrimes(num){
      let count = 0;
      for(let i = 2; i <= num; i++){
        let prime = true;
        for(let j = 2; j < i; j++){
          if(i % j == 0){
            prime = false;
            break;
          }
        }
        if(prime){
          count++;
          console.log("Prime number", i);
        }
      }
      return count;
    }
    
    console.log("total Prime numbers",countPrimes(100));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search