0

I am trying to do a problem to find the factors of a number. THe number is very very large.

The code that I am using is as follows:

def factors(n):
    result = []

    for i in range(1, n + 1):
        if n % i == 0:
            result.append(i)

    return result

print factors(5000000)

If I change the number to smaller number the program runs good, but when I increase the number, it throws an error. Is there any way to fix this ? Thanks.

Jd Baba
  • 5,658
  • 18
  • 58
  • 95
  • 2
    I guess [this](http://stackoverflow.com/questions/6800193/what-is-the-most-efficient-way-of-finding-all-the-factors-of-a-number-in-python) what you are looking for. – Thanakron Tandavas Apr 15 '13 at 20:20
  • Actually, I had found that solution before but I got an error while using this solution `def factors(n): return set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))` . The error I got is "NameError: name 'reduce' is not defined". Can you help me solve this error. – Jd Baba Apr 15 '13 at 20:23
  • It should works. Perhaps you could show your code. – Thanakron Tandavas Apr 15 '13 at 20:25
  • @Jdbaba - what version of python are you using? – Fredrik Pihl Apr 15 '13 at 20:26
  • @ Fredrik and Thanakron : I am using codeskulptor. You can find the code that I used here. http://www.codeskulptor.org/#user10_SyiG6thnPE_0.py I believe it implement python 2.6 – Jd Baba Apr 15 '13 at 20:27
  • 1
    From the homepage: "CodeSkulptor implements a subset of Python 2.6" Install/use a proper python distribution instead and everything will work! – Fredrik Pihl Apr 15 '13 at 20:30
  • 1
    [This answer](http://stackoverflow.com/questions/6800193/what-is-the-most-efficient-way-of-finding-all-the-factors-of-a-number-in-python/13999509#13999509) is one that will run on CodeSkulptor. – Jared Apr 15 '13 at 20:43
  • I still get the same error using that code on python idle as well. It says "global name reduce is not defined". – Jd Baba Apr 15 '13 at 20:43

0 Answers0