On 2015-02-16 at 12:28:35 -0600, Luis Mochan wrote:
> > I'm attaching a slightly commented versionin case it helps
Very nice code!
By the way, I noticed that you commented that you are using floor() from
POSIX instead of from PDL. Why is that?
I tried replacing the line
my $max=floor(sqrt($num));
with
my $max = pdl($num)->sqrt->floor;
and the whole script still works. Maybe it is just a matter of style?
Another way that works is
my $max = PDL::floor( PDL::sqrt( $num ) );
Regards,
- Zaki Mughal
> Forgot the attachment, sorry.
> #!/usr/bin/env perl
> use strict;
> use warnings;
> use feature 'say';
> use POSIX 'floor'; #I don't want pdl's floor, to avoid confusing 'sequence'
> use PDL::Lite;
> use PDL::NiceSlice;
>
> my $num=$ARGV[0];
> my $max=floor(sqrt($num));
> my $possible=PDL->sequence($max+1); #possible divisors<=sqrt($num)
> $possible->((1)).=0; #1 is not prime
> foreach(2..$max/2) { # eratosthenes sieve
> next unless $possible->(($_)); #skip non primes
> $possible->(2*$_:-1:$_).=0; # $_ is prime. Other multiples of $_
> # are not; zero them out.
> }
> my $primes=$possible->where($possible); # non zero elements are prime
> my $factors;
> my $allfactors=PDL->zeros(0);
>
> my $n=$num; # $n starts as number being factored
> do {
> $factors=$primes->where($n%$primes==0); #factors divide $n
> $n/=$factors->prod; # $n is another factor: 1 or prime or composite
> $allfactors=$allfactors->append($factors); #accumulate prime factors
> } while $factors->nelem; #until no more factors found
> # At this point either $num has been fully factored and $n==1 or $n is
> # (the only) prime factor larger than sqrt($num) (this fails in my
> # system for very large numbers for unknown reasons)
> $allfactors=$allfactors->append($n) unless $n==1; #append it if not trivial
> say $allfactors->qsort; # print result in increasing order
> _______________________________________________
> Perldl mailing list
> [email protected]
> http://mailman.jach.hawaii.edu/mailman/listinfo/perldl
_______________________________________________
Perldl mailing list
[email protected]
http://mailman.jach.hawaii.edu/mailman/listinfo/perldl