If is a divisor of , then is also a divisor of . Moreover, if is a perfect square, then the divisors \sqrt{n} and n /\sqrt{n} are the same.
Algorithm implementation
Read the input value of .
scanf("%d",&n);Iterate over divisors from to \sqrt{n} not inclusive.
for(i = 1; i < sqrt(n); i++)
if (n % i == 0)
{If is a divisor of , then is also a divisor of .
v.push_back(i);
v.push_back(n / i);
}Check if is a perfect square. In this case, add the divisor \sqrt{n} to the vector.
i = sqrt(n);
if (i * i == n) v.push_back(i);Sort the divisors in ascending order.
sort(v.begin(),v.end());Print all divisors in one line.
for(i = 0; i < v.size(); i++)
printf("%d ",v[i]);
printf("\n");Java implementation
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
int n = con.nextInt();
ArrayList<Integer> v = new ArrayList<Integer>();
for(int i = 1; i < Math.sqrt(n); i++)
if (n % i == 0)
{
v.add(i);
v.add(n / i);
}
int i = (int)Math.sqrt(n);
if (n % i == 0) v.add(i);
Collections.sort(v);
for(i = 0; i < v.size(); i++)
System.out.print(v.get(i) + " ");
System.out.println();
con.close();
}
}Python implementation
import mathRead the input value of .
n = int(input())We'll add the divisors of to the list .
lst = []Iterate over divisors from to \sqrt{n} not inclusive.
for i in range(1,int(math.sqrt(n))):If is a divisor of , then is also a divisor of .
if n % i == 0:
lst.append(i)
lst.append(n//i)Check if is a perfect square. In this case, add the divisor \sqrt{n} to the vector.
i = int(math.sqrt(n));
if n % i == 0: lst.append(i);Sort the divisors in ascending order.
lst.sort()Print all divisors in one line.
print(*lst)