I've been browsing the internet, but I can't find how to perform an algorithm to find prime numbers.
var cantidad = 100,j=2;
for(var i=2;i<cantidad;i++) {
for(;j<cantidad;j++) {
if(j%i==0 && (i==j || i==1)) {
console.log(j);
}
}
}
I tried the following: Trying from 2, since the prime numbers start from there and in the conditional I practically base it on the fact that if the remainder is 0 , and the divisor is the same number or 1, it would show it on the console, but it does not work.
So what is my mistake and how should it be?
Code
Explanation
Therefore, we have created the function:
Which in more natural language does the following:
Therefore in this loop:
We start looping through each of the iteration numbers checking through the function
primo()
if the number is prime and adding it to the array.Update
Due to the comments that I have seen, it seems that it has not been clear to you how this algorithm works, I proceed to explain it to you step by step.
Having the following function:
Run the Snippet to see how it works step by step.
The calculation of prime numbers has always been a very exciting topic from the point of view of efficiency, since among some of the practical applications that require very large prime numbers, is cryptography. One of the most used algorithms in this field is the RSA algorithm .
ISSUE
It is desired to calculate the number of prime numbers that exist in a range of N positive integers.
SOLUTION
In your solution approximation we have the classic conditional to determine if a number is prime or not:
This algorithm may be more efficient. If we analyze the part where we divide the candidate by the divisor, we are doing a series of unnecessary additional divisions. For this case, with a value of N=100 we have a total of 1133 iterations!!!
Explanation
A composite number n , is any non -prime natural number , which can be written in the form:
This means that both a and b (divisors of n ) have a maximum value that depends on each other.
Then, it is not necessary to iterate all the values from 2 to n looking for the possible divisors of n , it is enough to iterate until the square root of n . And since it won't be exact in most cases, we can skip the decimal part and iterate only to the nearest integer by default.
The improvement of the previous algorithm would be the following:
We have reduced the number of iterations to 236 iterations!!! to get the same result. Can it be made even more efficient?
Eratosthenes riddle
In the Sieve of Eratosthenes , you are asked to write all the natural numbers from 2 to N , then, starting with 2, you go through the entire list marking (crossing out) all the multiples of 2. Then you do the same with the next value of the list that has not been crossed out (for example 3), and so on until we have crossed out all the composite numbers between 2 and N. In the end, the numbers that have not been crossed out in our screen will be precisely the prime numbers we are looking for.
The algorithm would be something like this:
An example (taken from Wikipedia):
To implement this algorithm in Javascript, we can do the following:
In the above code, we have created an Array of 99 elements (from 2 to N there are N - 1 elements), and we have filled this Array with ones.
The code above calculates the square root of N and creates a for loop that goes from 2 to that value.
In the code above, each multiple of the value being iterated through is crossed out by setting its value in the list to zero.
In the code above, an Array called primes is created and the sieve is traversed. For each element not crossed out (whose value is 1), its position added to 2 ( index + 2 ) is saved in the Array of primes , which will be the value of the prime.
An implementation of this algorithm could be:
Note that this algorithm is even more efficient than the previous two, since, removing the fact that we must create the list of numbers and then go through it to get the primes, the result is achieved in just 113 iterations!!! .
I hope this makes clear the different ways to achieve the goal, with the Sieve of Eratosthenes being one of the most efficient.
Using a generator (ES6)
One possibility is to use a generator to simply iterate over it and return the next prime number in the sequence on each iteration.
The idea is simple and it is not necessary to store the prime values, what is done is to take the idea raised in the Eratosthenes sieve and create an iterable structure that implements the method
next()
, in such a way that each call to said method returns a prime value and so we can display the firstn
prime integers.The first thing is to have a way to iterate over the natural numbers, given an initial value. We can write a generator function that returns the sequence of natural numbers (from a value n) each time the function
next()
in the sequence is called.For example:
Now we need to create a generator function that takes each value of the sequence of natural numbers and, given a prime, returns all the values that are not multiples of that prime. This is a sieve over a sequence of values.
For example:
This function loops through a sequence of numbers and returns numbers that are not multiples of
primo
.Now that we have these 2 functions that return a sequence, we can write another generator function that from an initial value returns the next prime value. We achieve this by rewriting the sequence of natural values for the one that has the values that are not multiples of the previous prime.
For example:
In this function, a sequence is received that (ideally) starts at a prime value (let's say 2). Then, for each value of it, it creates a new sequence containing only the numbers that are not multiples of the generated prime, and returns that value on each call to
next()
.An example of the above code working to display the first 10 primes would be:
While this algorithm may not be as efficient as the ones presented above, it is another way to get primes using Javascript generators to get a sequence that will always return a prime every time the method is called
next()
.There is also this algorithm https://en.wikipedia.org/wiki/Sieve_of_Atkin is modern to find the prime numbers
It would be better for you knowing that the numbers in pairs except 2 are not prime, we take them out of the formula; We would have to get the odd numbers that could be 3, 5, 7, 9 but we know that 9 is a multiple of 3 and we emit it, we would only have 3, 5 and 7 left, since we already know the numbers from 1 to 10 which are the primes we can omit them and start from 11 adding two by two and thus we do not have to validate if it is even
Well I am based on this formula, I took it from the page: http://www.ceiploreto.es/sugerencias/ceibal/Primo_o_compuesto/cmo_saber_si_un_nmero_es_primo.html !
Use the console to appreciate the result. What I did was create two functions: The first is responsible for evaluating whether or not it is a prime number. And the second takes care of which number to which number you want to know the prime numbers.
Here the same answer but without comments
And if in case you wanted to print in the console all the numbers from beginning to end and it appears if it is or is not a prime number then:
I only add to the empty returns a console.log with a Templai String to add the values and I also add two if at the beginning. I hope it has been useful to you. Cheers !!!
To calculate the semiprimes of a number a, to a number b