Finding all natural numbers that multiply together to equal the user input

Viewed 40

I am new to programming and wanted to create a small program that can take a user input (a natural number) and returns all possible natural numbers that can be multiplied together to get to this outcome. Up until now I have created a "def find_factors" which seems to work and now I want to basically print always the first and the last numbers , divided by a "*", then second factor and second last factor, third and third last and so on...to display all possibilities.

**EXAMPLE the factors of 2048 would be [1,2, 4, 8, 16, 32, 64, 128, 256, 512, 1024,2048], so now I need some code that prints -->1 times 2048, 2 times 1024, 4 times 512, 8 times 256, 16 times 128, 32 times 64

CODE FOR FINDING FACTORS:

def find_factors(user_input):
    factors = []
    for x in range(1,user_input+1):
        if user_input % x == 0:
            factors.append(x)
    return factors

I would appreciate to hear any kind of comment or reply on how I could go about doing this, so thanks a lot for any insight.

4 Answers

I would check if the user input is divisible by the number, and then divide the user input by this number to get the other part. Then just print both numbers.
However this would not be a complete factorisation. Just giving possibilities of two whole numbers multiplied to give the user input.

I believe the below code will accomplish what you need.

def print_factors(x):  
    factors = []
    for i in range(1, x + 1):
        if x % i == 0:
        factors.append(i)
    for i in range(1,int(len(factors)/2)+1):
        print(f'{factors[(i-1)]}*{factors[-i]}')

num = 2048
print_factors(num)

Here's how I would do it:

def factors(n):
    return [i for i in range(1, n//2+1) if n % i == 0] + [n]

factors(108)
factors(2048)

Output:

[1, 2, 3, 4, 6, 9, 12, 18, 27, 36, 54, 108]
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048]

Note:

This is fine for relatively small numbers. Very large numbers need to be handled quite differently.

Also:

You could (not should) use this to determine if a number is prime. If the length of the list returned by this function is exactly 2, then the input N is a prime number because its factors will be 1 and N

to search for factors you only need to look at all the numbers less than the square root of your input, this allows you to find all the factors

for example, N = 100 the loop

for x in range(1,int(sqrt(N))+1):
   if N % x == 0:
      print(x,"*",N/x)

will print all the factors in the format that you need,

1 * 100
2 * 50
4 * 25
5 * 20
10 * 10

this significantly reduces the number of iterations you have to do to find the factors, e.g. for 1000000 the number of iterations is 1001

Related