isprime.py - find factors of numbers

By aboutscript on Jan 05, 2013

Find out if a number is prime. If it isn't, you'll get a list of factors. It's useful for finding GCM and other miscellaneous things about numbers.

For example, I was making a 1280x720 picture and I needed to know how it could be broken into squares.

$ ./isprime.py
Number: 1280
[2, 4, 5, 8, 10, 16, 20, 32, 40, 64, 80, 128, 160, 256, 320]
Number: 720
[2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, 30, 36, 40, 45, 48, 60, 72, 80, 90, 120, 144, 180, 240]

Now I know it can be divided by 80 each way; and with a little division and then a little multiplication, 1280x720 can be made of 144 80x80 squares. Maybe you don't run into things like this every day, but I do :-)

#!/usr/bin/env python

def isprime(n):
    return [x for x in range(2, n / 2) if n % x == 0] or False

if __name__ == '__main__':
    while True:
        n = input('Number: ')
        print isprime(n)

Comments

Sign in to comment.
Conscious   -  Jan 05, 2013

If you're listing factors, you should also list 1 and n, to be complete
edit: also, shouldn't the 1280 one be returning 640 too?

 Respond  
BlueThen   -  Jan 05, 2013

Should line 4 be returning True if the number has no known multiples?

 Respond  
Hawkee   -  Jan 05, 2013

Much better. Although I'd give it a more descriptive title. It'll draw more people.

Hawkee  -  Jan 06, 2013

There you go. You should be able to pick up more search traffic that way.

Sign in to comment

Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.