Type something to search...
Solution to Day 7 of 7 Days of JS

Solution to Day 7 of 7 Days of JS

  • JavaScript
  • Challenge
  • Lautaro Lobo
  • 05 Dec, 2019

When writing this solution, I realized that I needed a function that returns true if a number is prime. So I wrote that function first:

function isPrime(n)\{
  let i = 2, rem = true;
  while (i < n && rem)\{
    rem = rem && n % i != 0;
    i++;
  }
  return rem;
}

console.log(isPrime(17))

And once I had that, I was ready to write primesUntil, which you can see here:

function primesUntil(n)\{
  let x = 1, i = 0;
  while(i < n)\{
    x++;
    if (isPrime(x))\{
      console.log(x);
      i++;
    }
  }
  return 'Those are the first ' + n + ' primes.'
}

console.log(primesUntil(5))

It鈥檚 possible to write both functions with for loops instead of while loops. If you are just starting out with loops in JavaScript, you should try to do that.

Any questions? Write a comment!

This is the end of our journey. But don鈥檛 worry, I鈥檒l be back soon with more challenges. If you don鈥檛 want to miss them, follow me on DEV && Pinterest && Twitter && I have a newsletter! 馃槉

See you soon!


Share it!

Related Posts