@
Radar
The code you found is one of the usual naive implementations of prime number finding, and is very inefficient for larger numbers. Try running it for numbers up to 1 million - see how long it takes :+)
The problems with it are:
It divides by
every number less than
i
, as
ne555 pointed out, one only needs to check each prime number less than
sqrt(i)
. So as 1 example you are checking for division by 2, 4 , 6 ,8 ... which is obviously a waste.
It's testing
all the numbers less than
i
, but it is only necessary to go to sqrt(i). So if you went to 1 million, you only need to test up to 1,000.
shadowmouse's algorithm is much better.
Although there is one modification:
If N is the number you want to remove multiples of, first remove N
2 , all the numbers up to there will be prime (as long as one has worked through the list sequentially to this point), then remove multiples of N from there on.
This is called Euler's algorithm and is detailed on the wiki page, near the end.
@
csstudent123
Here is a link to a segmented prime sieve, but note that if you submit this code for your assignment, prepare to get busted by your teacher.