Any Better logic for this problem..

Chris Angelico rosuav at gmail.com
Thu Jun 9 05:25:06 EDT 2011


On Thu, Jun 9, 2011 at 7:06 PM, Chris Rebert <clp2 at rebertia.com> wrote:
> On Thu, Jun 9, 2011 at 1:31 AM, Ganapathy Subramanium
> <sganapathy.subramanium at gmail.com> wrote:
>> Hi Guru's,
>> I'm working on a solution to find the prime factor of the number
>> This part of the code works.. http://www.pastie.org/2041584
>
> For the archives, that code is:
>
> for items in prime_numbers:
>    if num % items == 0:
>        prime_factors.append(items)
>
> print 'The prime factors are : ' , prime_factors

Prime factors don't quite work that way. The prime factors of 24, for
instance, are 2, 2, 2, and 3. But if you're looking for _unique_ prime
factors, then this will work.

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. (Be sure to
include the square root itself; range(2,sqrt(num)) won't work if num
is a perfect square. Use range(2,sqrt(num)+1) for safety.) That will
save a fair amount of effort. Also, if you divide num by each factor
found, it'll make the numbers smaller, which may be faster.

Hope that helps!

Chris Angelico



More information about the Python-list mailing list