Hi guys, new here, and new to python. And I thought I would ask for a bit of guidance on this piece of code I'm working on.

The following block of code is supposed to output all positive factors of the entered integer. However, it does not work properly. The range of num goes from 0 to num. However, modulo by zero is impossible. I have tried limiting the range with

range(1,num)

. But it does not provide the correct outputs.

My Bugged Code:

num = int(raw_input("What number would you like to know the factors of? "))

print "The positive factors of " + num + "are: "

for test in range(num): #range goes from 0 -> num, on the first instance,test  = 0

    if num%test == 0:   #num cannot be modulo by 0
        print num

Can anyone provide some sort of guidance, and point me in the right direction?

Thanks,
ZigZag

At line 8, it should be print test .

Indeed it should be. >>>print test coupled with the range(1,num) modification it appears the code runs properly. It also appears that despite my efforts, I have much to learn. Thank you for pointing me in the right direction.

+1 for you sir!

Cheers,
ZigZag

You generate though all factors, not only prime factors, and the print on line three does not also work as num is integer. The number of possible factorings increase much faster than number of prime factors (as for each number which has power n you take every power 1..n => all other factorings n times) Also you do linear amount of checks instead of reducing the number by factors. In the case of big numbers it is important to use xrange not range, as xrange does not produce list of all numbers in memory (try 1234567890 for the input number). At least you could stop at sqrt(number), if you realize that if factor is a factor then also number/factor is factor >= sqrt(number).

num = int(raw_input("What number would you like to know the factors of? "))

print "The positive factors <= square root of the number with it's pair for number %s are: " % num 

for test in xrange(1, int(num**0.5)): # xrange does not generate full list in memory

    if num%test == 0:   #num cannot be modulo by 0
        print test, num//test

Edited 6 Years Ago by pyTony: n/a

This article has been dead for over six months. Start a new discussion instead.