Algorithm Analysis
If is a divisor of the number , then will also be a divisor of the number . In this case, if is a perfect square, then the divisors and coincide.
Algorithm Implementation
Read the input value .
scanf("%d",&n);
Iterate over divisors from 1 to not inclusively.
for(i = 1; i < sqrt(n); i++) if (n % i == 0) { // If i is a divisor of n, then n / i will also be a divisor of n. v.push_back(i); v.push_back(n / i); }
Check if is a perfect square. In this case, add the divisor 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 math n = int(input()) list = [] for i in range(1, int(math.sqrt(n))): if n % i == 0: list.append(i) list.append(n//i) i = int(math.sqrt(n)); if n % i == 0: list.append(i); list.sort() print(*list, sep=" ")