in reply to is_a_prime test?

Hello,

First things first-- please use the code tag around your source code. Also, preview is a wonderful idea before creating a post.

How do you know the code is hanging? Consider putting some logic in that will update you every x numbers in the loop. Basic debugging is a good skill to learn, and usually starts with a print. Now consider that you only have to check the numbers up to the square root of the number you are testing for prime, and you only need to check the odds after the number 2.

Replies are listed 'Best First'.
Re^2: is_a_prime test?
by raybies (Chaplain) on Oct 25, 2010 at 12:17 UTC
    ...and really you only have to check other primes (they're all odd numbers) after 2, which I suppose you could generate over time in an array, at least to some orders of magnitude, so that subsequent calls to said routine were further optimized...
      ...and really you only have to check other primes (they're all odd numbers) after 2, which I suppose you could generate over time in an array, at least to some orders of magnitude, so that subsequent calls to said routine were further optimized...

      That's what I was going to suggest. If you created an is_even function, you could rule out (on average) half of your iterations by ruling out the even numbers first. Of course that would require a special case where n=2, but that would be a single-liner.

      Even as optimized as you can be, throwing it really large numbers will always take a very long time, so to give the user some kind of indication that your program is not hung, consider putting in some type of progress indicator. Since you know what the number is, you'd know about how many factors you'd have to check (is it 1 to n, or something else that's fixed?) so you could add something like this:
      # Used for progress indicator select STDERR; $| = 1; ... # Progress indicator, final value $progress = ($count / $total_count) * 100; printf "Progress: %4.1f\%\r",$progress; # Set carriage returns back to normal after progress indicator is comp +lete select STDOUT; print "\n"; $| = 0;
      This works really well for a script I use that connects to several hundred servers. Of course it's only useful when you're executing it from a shell, as opposed to cron or some other background process.

      Hope that helps.