in reply to Perl Not Releasing Memory

rekcah,
First, I would like to say Welcome to the Monastery and to Perl. Ok - everything everyone else has said is correct. There will be arguments on both sides on what I am about to say, but Perl was designed with deep roots in Unix - which originally didn't provide a mechanism to release memory back to the operating system. With this said, it is fairly adept at re-using memory without requesting more as long as the design of your program allows it to do its job. Future releases of Perl may even release memory back to the OS, but in the interim - lets fix your code. You will have to adapt it to your specific needs, but this should give you an idea.
#!/usr/bin/perl -w use strict; for my $test_number (5 .. 1000) { next unless ($test_number % 2); my ($prime , $factor) = IsPrime($test_number); if ($prime) { print "$test_number is prime\n"; } else { print "$test_number is not prime - divisible by $factor\n"; } } sub IsPrime { my $input = shift; my $t_number = 3; while ($t_number < sqrt($input)) { return (0, $t_number) unless ($input % $t_number); $t_number += 2; } return 1; }

Replies are listed 'Best First'.
Re: Re: Perl Not Releasing Memory
by Anonymous Monk on Jul 02, 2003 at 13:51 UTC

    There are faster ways to decide this problem, as well. I'm no mathematician, but your algorithm is dividing by all odd factors between 3 and sqrt(x); this can be improved by dividing by all *prime* factors between 3 and sqrt(x).

    Since you're already finding all these numbers, just use dynamic programming-- when you find a prime, hash it for later reference. Then in your loop just go through the keys of your hash.

      Anonymous Monk,
      As tilly would say, I am a displaced mathematician. I realize the inefficiency of the algorithm and I appreciate you pointing it out. In fact, the code itself could have been made a lot more concise by sacrificing readability. I was just trying to help the new monk out. I figured it was easy enough to understand and modify for their purposes.

      Cheers - L~R