Question

I'm new to programming and I am trying to write a program that takes a positive integer n from input, and then outputs all factorizations of n.

For example if n=10 the program would output
1 times 10 equals 10
2 times 5 equals 10
5 times 2 equals 10
10 times 1 equals 10

I believe the easiest way to do it is to use an if statement nested within for loops. Can anybody provide me with any guidance to help create this? So far I have...

n = int(input())
a = 0
b = n
for a in range(0, n):
    if a * b !=n:
      continue
    if a * b ==n:
      print (a+ "times" +b+ "equals" +n)
    a=a+1
    b=n-1

But for some reason it isn't working. I think I have the right general idea but my code is obviously incorrect.

Was it helpful?

Solution

There are a few issues with your code, but also with your logic. You are increasing a twice (with for and addition), b becomes n-1 the first time through the loop and stays that way, but even if it didn't (eg b = b - 1), it wouldn't work, because if you are increasing a and decreasing b simultaneously, you won't find the correct values unless they happen to match by chance.

Other than that, it's unnecessary to check for a * b != n, you need to call str on the integers to add them to strings and the 0 in your range call is redundant.

whncode's answer is an elegant solution (except for a couple of errors I tried to correct), but to use your logic, you might do this:

for a in range(1, n+1):
    for b in range(1, n+1):
        if a * b == n:
            print str(a) + " times " + str(b) + " equals " + str(n)

OTHER TIPS

n = 10
for divisor in range(n, 0, -1): # reverse range
    if (n%divisor == 0):       # if modulo is 0
        print("%d times %d equals %d", (n/divisor, divisor, n)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top