Skip to content
Advertisement

Prime numbers – I need clarification on code implementation

This is the code I know:

JavaScript

But is this ok if you’re looking for prime numbers:

JavaScript

Output:

JavaScript

And also is there much difference in time complexity?

Advertisement

Answer

Your code is incorrect. This code only works because you are taking the value of n as 30, for a greater number like 1000 this will produce an incorrect result. List arr = [2,3,5,7]; // already known

JavaScript

Your code will return 231 prime numbers when there are actually only 168 prime numbers. This is because you are not considering the future prime numbers that can only be divided by a prime number between 7 to that number.

eg: 121 will be returned by you as prime but it is a multiple of 11

Extending your pattern. Though this will be faster since it has reduced a number of division operations but due to two loops, it will still be N square.

Here I am simply only dividing numbers from the existing prime numbers collection and adding them in the collection if prime is found tobe used in next iteration for division.

JavaScript

You can look a faster pattern here. Which is the fastest algorithm to find prime numbers?

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement