Python Program To Find Factors Of A Number Using Function

There are a lot of methods in Python to find the factor or divisor of a given number and almost all the methods can be implemented using a function. Because one of those methods is also a method of recursion, which means a function call inside a function. Let’s start with all those methods. We are going to cover three concepts in this article to find the factor/denominator.

01. Method

Using For Loop.

def factors(x):
    print("Factors Of {}:".format(x))
    for i in range(1,x+1):
        d=x%i
        if d==0:
            print(i)

n=18
# n = int(input("Enter Integer Value: "))
factors(n)

Output:

1
2
3
6
9
18

Read More: Python Program To Sort Array Elements In Ascending Order

02. Method

Using While Loop.

def factors(x):
    print("Factors Of {}:".format(x))
    i = 1
    while(i < (x+1)):
        d=x%i
        if d==0:
            print(i)
        i+=1

n=18
# n = int(input("Enter Integer Value: "))
factors(n)

Output:

1
2
3
6
9
18

Read More: Python Program To Print Fibonacci Series

03. Method

Using Recursion.

def factors(x,i):
    if(x >= i):
        if ((x%i)==0):
            print(i)
        factors(x,i+1)

n=18
# n = int(input("Enter Integer Value: "))
factors(n,1)

Output:

1
2
3
6
9
18

 

USEFUL POSTS:

  1. Python Program to Check Given Number is Odd Or Even Using Counter
  2. Python Program to Check Given Number Is Armstrong Or Not
  3. Python Program To Find Sum Of Arithmetic Progression Series

Leave a comment