Skip to content
October 8, 2007 / wj32

Factor for Python

Factor some numbers…

"""
    Factor a number
    
    Wj.
"""

# Simple factoring
def factor(n, noduplicates = False):
    intn = int(n)
    factors = {}
    lastfactor = n
    i = 0
    
    # 1 is a special case
    if n == 1:
        return {1: 1}
    
    while 1:
        i += 1
        
        # avoid duplicates like {1: 3, 3: 1}
        if noduplicates and lastfactor <= i:
            break
        
        # stop when i is bigger than n
        if i > n:
            break
        
        if n % i == 0:
            factors[i] = n / i
            lastfactor = n / i
    
    return factors

if __name__ == "__main__":
    import sys
    
    print "Enter an integer:"
    number = sys.stdin.readline()
    print "Factors: " + str(factor(int(number), True))

5 Comments

Leave a Comment
  1. Tim / Sep 9 2008 7:49 am

    I think that you can make it a bit faster by stopping when i is greater than n**0.5. You could also then eliminate the check for duplicates.

  2. panos / Mar 2 2011 7:51 am

    Variable “intn” created at line 9 is never used.

    Perhaps the correct line is:
    “n = int(n)”
    ?

  3. Watermelon / Jul 28 2011 10:47 am

    A bit slow, and such a long code, here is one i just wrote:
    im not sure if the indentation will be right after i comment it, but if you know python you can figure it out:

    #011011000110111101101100
    x= int(raw_input (“Enter a number to get its factors: “))
    factorlist=[]
    for a in range (1,x):
    for b in range (1,x):
    if a*b==x:
    if [b,a] not in factorlist:
    factorlist.append([a,b])

    if factorlist==[]:
    print “This Number has no factors ”

    print factorlist

    raw_input()

  4. manel / Nov 2 2011 12:50 am

    Sorry but none of your code do what they should.

    lets say factoring number 8. The right answer is 2x2x2 = 2^3 = 8
    so the right answer always has to contain prime numbres.
    Take a look a Euclides algoritm !!!!
    Sorry for this news from Barcelona.

Trackbacks

  1. 2009 is not a prime number. A python program to compute factors. | /var/log/mind

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.