April 04, 2009 Re: project euler #10: optimization with primes | ||||
---|---|---|---|---|
| ||||
Posted in reply to Michael P. | Michael P. wrote: <snip> >>> int sum = 2; You have a serious bug here. Can you see what it is? <snip> >> One thing that may help a little is that you need only loop from 2 to sqrt(n) in the isPrime function, otherwise you end up testing for factors > sqrt(n) twice. A factor over sqrt(n) must have a corresponding factor less than sqrt(n) for a given n. > > That helped. Ran in about 10-15sec I think after doing that. Thanks for the help everyone. I've optimised your version to compare against a pre-calculated sqrt(n), and check only against 6k-1 and 6k+1 (in both loops). On my Windows Vista box with a 2.4GHz CPU, it takes just under 6 seconds to add the primes up to 10 million. That said, the other day I wrote an even faster prime finder, which takes just over 2.5 seconds to do the same. Stewart. |
April 04, 2009 Re: project euler #10: optimization with primes | ||||
---|---|---|---|---|
| ||||
Posted in reply to Tiago Carvalho | Tiago Carvalho wrote: <snip> > I've done this a while ago. But if I remember correctly you only need to verify 2, 3, and after that all primes will be forms of 6k+1 or 6k-1. This made my code a lot faster at the time. > > Don't know if this is faster in this case since you have to store values in an array (or other storage), but if you store the calculated primes, you only need to test the current value against those. See my reply to Michael. My fast prime finder keeps an array of primes, and maintains a slice of this array up to the square root of the number being tested. > If a umber can't be divided by none of the primes below it, it's prime. No, if it can't be divided by _any_ of the primes below it, it's prime. Stewart. |
Copyright © 1999-2021 by the D Language Foundation