Factor Finder
A number’s factors are any two other numbers that, when multiplied with each other, produce the number. For example, 2 × 13 = 26, so 2 and 13 are factors of 26. Also, 1 × 26 = 26, so 1 and 26 are also factors of 26. Therefore, we say that 26 has four factors: 1, 2, 13, and 26.
If a number only has two factors (1 and itself), we call that a prime number. Otherwise, we call it a composite number. Use the factor finder to discover some new prime numbers! (Hint: Prime numbers always end with an odd number that isn’t 5.) You can also have the computer calculate them with Project 56, “Prime Numbers.”
factor_finder.py
1"""Factor Finder, by Al Sweigart al@inventwithpython.com
2Finds all the factors of a number.
3This code is available at https://nostarch.com/big-book-small-python-programming
4Tags: tiny, beginner, math"""
5
6import math, sys
7
8print('''Factor Finder, by Al Sweigart al@inventwithpython.com
9
10A number's factors are two numbers that, when multiplied with each
11other, produce the number. For example, 2 x 13 = 26, so 2 and 13 are
12factors of 26. 1 x 26 = 26, so 1 and 26 are also factors of 26. We
13say that 26 has four factors: 1, 2, 13, and 26.
14
15If a number only has two factors (1 and itself), we call that a prime
16number. Otherwise, we call it a composite number.
17
18Can you discover some prime numbers?
19''')
20
21while True: # Main program loop.
22 print('Enter a positive whole number to factor (or QUIT):')
23 response = input('> ')
24 if response.upper() == 'QUIT':
25 sys.exit()
26
27 if not (response.isdecimal() and int(response) > 0):
28 continue
29 number = int(response)
30
31 factors = []
32
33 # Find the factors of number:
34 for i in range(1, int(math.sqrt(number)) + 1):
35 if number % i == 0: # If there's no remainder, it is a factor.
36 factors.append(i)
37 factors.append(number // i)
38
39 # Convert to a set to get rid of duplicate factors:
40 factors = list(set(factors))
41 factors.sort()
42
43 # Display the results:
44 for i, factor in enumerate(factors):
45 factors[i] = str(factor)
46 print(', '.join(factors))