in reply to Re: Finding all divisors of an integer
in thread Finding all divisors of an integer

Sidhekin,
I would not worry about optimizing this, unless you need it for very many or very big numbers
Indeed, the node was updated after you (and I) already started posting. I would say that you only need to go to $number / 2 though.

@divisors = grep { $number % $_ == 0 } 1 .. sqrt($number);
I think you are thinking of prime factorization here. You can stop there to determine primeness but not to determine all factors.

Cheers - L~R

People should not be allowed to touch keyboards early in the morning (weekend) without proper caffeine intake. I completely missed the push in the second line of code
  • Comment on Re^2: Finding all divisors of an integer

Replies are listed 'Best First'.
Re^3: Finding all divisors of an integer
by Sidhekin (Priest) on Jul 03, 2004 at 14:16 UTC

    @divisors = grep { $number % $_ == 0 } 1 .. sqrt($number);
    I think you are thinking of prime factorization here. You can stop there to determine primeness but not to determine all factors.

    You somehow miss the second line of my optimized solution. It adds the other half of the divisors. :-)

    push @divisors, map {$number == $_*$_ ? () : $number/$_} reverse @divi +sors;

    For every divisor above the square root, there is a corresponding divisor below the square root. Symmetrical optimization. :-)

    print "Just another Perl ${\(trickster and hacker)},"
    The Sidhekin proves Sidhe did it!

    A reply falls below the community's threshold of quality. You may see it by logging in.
A reply falls below the community's threshold of quality. You may see it by logging in.