-3

As per title, I've solved the following kata https://www.codewars.com/kata/5262119038c0985a5b00029f and here is my solution:

 let isPrime = (num) => {
     for (let i = 2; i < num; i++)
         if (num % i === 0)

         return false;
    return num > 1;
}

The kata description says the following:

Define a function that takes one integer argument and returns logical value true or false depending on if the integer is a prime.

Per Wikipedia, a prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.

Requirements You can assume you will be given an integer input. You can not assume that the integer will be only positive. You may be given negative numbers as well (or 0). NOTE on performance: There are no fancy optimizations required, but still the most trivial solutions might time out. Numbers go up to 2^31 (or similar, depends on language version). Looping all the way up to n, or n/2, will be too slow.

So my question is, since my solution is timing out, how can I improve it? Thanks!

geek101
  • 87
  • 7
  • 2
    *"Looping all the way up to n, or n/2, will be too slow."* So, you need to do a little research and figure out how to change your loop. – user3386109 Jan 30 '22 at 19:38
  • It seems to me that your `if` loop body is empty -- is that intended? (Edit: It's possibly just because of the textarea messing up the indentation) – Astrid E. Jan 30 '22 at 19:39
  • @user3386109 thanks a lot! incredibly helpful! why did you think I wrote this post? – geek101 Jan 30 '22 at 19:47
  • @AstridE. no parenthesis but the code is working :) – geek101 Jan 30 '22 at 19:52
  • 1
    You should show your research efforts. Actually you should take the comment of user3386109 to heart. They actually point to the part that can be improved and which you should research... – trincot Jan 30 '22 at 19:55
  • @trincot I didn't even know where to start looking, that's why I asked here. Depending on the person who will answer, this community can be the absolute best or worst. Sometimes it seems like the concept of being supportive is really foreign to some people. I got my answer anyway but please, some of you really need to be kinder. Thanks anyway. – geek101 Jan 30 '22 at 20:05
  • Does this answer your question? [c++ function to check if a number is a prime](https://stackoverflow.com/questions/70906393/c-function-to-check-if-a-number-is-a-prime) – interjay Jan 30 '22 at 20:09
  • 1
    I don't understand why you perceive unkindness here. We are all volunteers who are here to help. We believe we help most if we help you to help yourself. The very first comment gave a good indication where to look. Why not appreciate that instead of replying with *"why did you think I wrote this post"*... – trincot Jan 30 '22 at 20:13

1 Answers1

0

Look up Sieve of Eratosthenes and you can find out at what point you can stop incrementing i.

Spoiler: sqrt(num)

heothesennoc
  • 486
  • 4
  • 8