In: Computer Science
The above question can be solved by iterating over all the numbers upto sqrt(n) where n is the number whose factors are to be found. If any number i divides n, then i and n/i are the two factors of the number. In case the number is a perfect square then, the factor i where i*i = n needs to be printed only once. The code is given below:
import math
def factors(n):
i=1#Initialize
while i<=sqrt(n):
if (n%i==0):#Incase i divides n
if(n/i==i):#If i is the square root of n
print(i)#print the factors
else:
print(i)#print the factors
print(int(n/i))#print the factors
i = i+1
if __name__=="__main__":
factors(100)
Sample Run:
Alternate solution:
We could also change the condition in the while loop to i*i<=n. The code is given below:
def factors(n):
i=1#Initialize
while i*i<=n:
if (n%i==0):#Incase i divides n
if(n/i==i):#If i is the square root of n
print(i)#print the factors
else:
print(i)#print the factors
print(int(n/i))#print the factors
i = i+1
if __name__=="__main__":
factors(100)
Sample Run:
-----------------------------------------------------------------------------------
In case of any doubts or queries, please write in comments.:)