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:
JavaScript
x
8
1
number=42
2
factor_list=[]
3
for num in range(1,number+1):
4
num=number/num
5
if (number%num)==0:
6
factor_list.append(num)
7
print(factor_list)
8
Output:
JavaScript
1
2
1
[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]
2
Advertisement
Answer
As to why your program does not work, let’s see what is going on step by step:
JavaScript
1
8
1
number=42
2
factor_list=[]
3
for num in range(1,number+1): #for num in [1, 2, 3, 4, 5... 42] (Let's take 28 for example)
4
num=number/num # num = 42 / 28; num = 1.5 now
5
if (number%num)==0: # 42 mod 1.5 == 0.0
6
factor_list.append(num) # so we add 1.5 to the list.
7
print(factor_list)
8
See the problem in logic now?