Thursday, 4 November 2010

Finding if a number is a prime

Update 06/04/2012
Modified the for loop as proposed by Alan (comment #1) which makes the method roughly twice as fast.


Alan said...

Afternoon, Andy.

Afraid I don't like this: I think you're checking twice whether the number is even or not, and you test a whole load of unnecessary divisors.

Wouldn't for (long i=3; i<=maxCheck; i+=2) be an improvement? But I'm sure we can do better still.

Andy Till said...

Hi Alan

That's a lot better! I will update the post to reflect your proposed changes.

I came up with this while I was working on a couple of Project Euler problems so didn't bother to optimise too much as the data sets aren't too big.