DEV Community

Vuyisile Lucas Ncipha
Vuyisile Lucas Ncipha

Posted on

Find Factors of A number

In this post I am going to share with you guys how to find the factors of a number using python.

This may help a lot of you with the for loops on action.

So what we are going to create is a function that will take a number that we want to find its factors as a parameter and then return all the factors as a list.

E.g:

   factors = factors_of(10)
   print(factors)

Results:

   [1,2,5,10]

Let us get into this function.

Step 1: Define a function


Is very important to give your function an meaningful name.

   def factors_of(number):

The reason I chose factors_of is because it gives saves you time and energy to put a comment. Using meaningful name can save you from writing a comment to explain what does a function does.


Step 2: Create a temporary list


This list is the one that is going to be returned carrying all the factors.

   temp = list()

Sorry I migrated to python from c#, so I am used to instantiating a data type hence I said temp = list() instead of temp =[]. But I think for memory cache purposes, list() is better than [] just append is better than +=. If I am wrong with this please feel free to comment.


Step 3: Create A loop from 1 to the number

This loop must with the number we are looking it's factors. We are going to use the built-in function *range(seed,max-1,step)

   for i in range(1,number+1):

Plus 1 because we want the number itself to be included because according to the formula of a range, the number is excluded.


Step 4: Use a condition with % operator

For us to find if a number is a factor we must find a remainder of 0 if we devide with it. Lucky we will just % to find remainder. Then we append the number to the list

   #line for the loop
       if number%i==0:
           temp.append(i)

Then lets return the list.

Code is full:

   def factors_of(number):
       temp = list() 
       for i in range(1,number+1):
           if number%i==0:
               temp.append(i)
       return temp

So if we go back to our example but with a different number let's check the results

   factors = factors_of(20)
   print(factors)

Results:

   [1,2,4 5,10,20]

I hope you enjoyed the post and it was helpful for you. Cheers

Top comments (2)

Collapse
 
curtisfenner profile image
Curtis Fenner

You can make this really concise with list comprehension:

def factors_of(n):
    return [k for k in range(1, n+1) if n % k == 0]
Collapse
 
nciphalucas profile image
Vuyisile Lucas Ncipha • Edited

YES, But a lot of people are new to python programming, if that was not the case I would have used lambda function to solve this.

   factors_of = lambda number: [k for k in range(1, number+1) if number%k==0]