Reputation: 13
I'm trying to code a program that prints the factors of a number, just as shown in the attached image, but the outcome is totally not what I'm expecting. (I just want the code to return factors of the specified number.) What am I doing wrong and what is the correct way of doing it?
Code:
number=42
factor_list=[]
for num in range(1,number+1):
num=number/num
if (number%num)==0:
factor_list.append(num)
print(factor_list)
Output:
[42.0, 21.0, 14.0, 10.5, 7.0, 6.0, 5.25, 3.5, 3.0, 2.625, 2.0, 1.75, 1.5, 1.3125, 1.0]
Upvotes: 1
Views: 152
Reputation: 26825
In Python, the division operator / will result in a float data type even if the values either side of it are int. For integer division you should use //
Having said that, what you need here is the modulo operator.
Here's a concise (but not necessarily most efficient) way of achieving your objective:
def factors(n):
return [1] + [x for x in range(2, n + 1) if n % x == 0]
print(factors(4203))
Output:
[1, 3, 9, 467, 1401, 4203]
Fun fact:
If the length of the returned list from this function is 2 then n must be a prime number. Don't go using this function to test for primes though as it would be woefully inefficient
Upvotes: 0
Reputation: 7971
As to why your program does not work, let's see what is going on step by step:
number=42
factor_list=[]
for num in range(1,number+1): #for num in [1, 2, 3, 4, 5... 42] (Let's take 28 for example)
num=number/num # num = 42 / 28; num = 1.5 now
if (number%num)==0: # 42 mod 1.5 == 0.0
factor_list.append(num) # so we add 1.5 to the list.
print(factor_list)
See the problem in logic now?
Upvotes: 0
Reputation: 3009
Just remove the 4th line i.e num=number/num
which produces quotients. you are trying to find modulus of number
from those quotients that is the reason you are getting wrong answer. Here is the modified code which works.
number = 42
factor_list=[]
for num in range(1,number+1):
if(number%num==0):
factor_list.append(num)
print(factor_list)
Upvotes: 1