code for printing factors of a number
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.) Can anyone please help me understand what I'm 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)
CodePudding user response:
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?
CodePudding user response:
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)
CodePudding user response:
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
CodePudding user response:
You just need to do this:
for i in range(1, number 1):
if number % i == 0:
print(i)