Contents
Find All Factors of a Given Number
In this program, we read a number from user, and find all the factors of this number.
Input
n
where n>0
Program
We write findFactors()
function that takes n
as parameter, and returns a list of all the factors for given number.
Python Program
def findFactors(n):
factors = []
for i in range(1,n+1):
#check if i is a factor
if n % i == 0:
factors.append(i)
return factors
n = int(input('Enter n : '))
result = findFactors(n)
print(result)
Output #1
Enter n : 10
[1, 2, 5, 10]
Output #2
Enter n : 512
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
Program for Efficiency
We can make the above program more efficient. How? If i is a factor of n, then n/i is also a factor. We can take advantage of this and limit our iterations to n/i instead of n.
Python Program
def findFactors(n):
factors = []
i = 1
while i < (n / i):
#check if i is a factor
if n % i == 0:
factors.append(i)
#if i is a factor, then n/i is also a factor
factors.append(int(n/i))
i += 1
factors.sort()
return factors
n = int(input('Enter n : '))
result = findFactors(n)
print(result)
Output #1
Enter n : 10
[1, 2, 5, 10]
Output #2
Enter n : 512
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
Related Tutorials
- Python – Largest of Three Numbers
- Python – Smallest of Three Numbers
- Python String – Find the number of overlapping occurrences of a substring
- Python Program to Add Two Numbers
- Numpy sqrt() – Find Square Root of Numbers
- Python – Sum of Two Numbers
- Reverse a Number in Python
- Python – Factorial of a Number
- How to Swap Two Numbers in Python?
- How to Get Number of Axes in Pandas DataFrame?