Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #7326

Re: Any Better logic for this problem..

References <BANLkTinWq5pjX2+0OVRvm1Xs7ESmYf0qcw@mail.gmail.com> <BANLkTimicVsm7EGMsVu0bXRsa7714MKpwA@mail.gmail.com> <mailman.48.1307611509.11593.python-list@python.org> <95d0drFa9jU1@mid.individual.net>
Date 2011-06-10 08:44 +1000
Subject Re: Any Better logic for this problem..
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.62.1307659489.11593.python-list@python.org> (permalink)

Show all headers | View raw


On Fri, Jun 10, 2011 at 8:39 AM, Gregory Ewing
<greg.ewing@canterbury.ac.nz> wrote:
> Chris Angelico wrote:
>
>> Rather than find all prime numbers up to num, stop at sqrt(num) - it's
>> not possible to have any prime factors larger than that.
>
> That's not quite true -- the prime factors of 26 are 2 and 13,
> and 13 is clearly greater than sqrt(26).

Oops! My bad. I was thinking in terms of the "divide and conquer"
algorithm, whereby the 13 would be the residuum after dividing by 2...

> However, once you've divided out all the primes up to sqrt(n),
> whatever is left, if greater than 1, must itself be prime, so
> you can add it to your prime factors and stop.

... which is effectively the same as you describe here. It's a small
algorithmic change but an extremely advantageous one.

If you _don't_ look for the residuum, then you stop at n/2 instead of
sqrt(n). Either way, though, you don't need to list the primes all the
way up to n, which will improve performance significantly.

Chris Angelico

Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

Re: Any Better logic for this problem.. Chris Angelico <rosuav@gmail.com> - 2011-06-09 19:25 +1000
  Re: Any Better logic for this problem.. Gregory Ewing <greg.ewing@canterbury.ac.nz> - 2011-06-10 10:39 +1200
    Re: Any Better logic for this problem.. Chris Angelico <rosuav@gmail.com> - 2011-06-10 08:44 +1000

csiph-web