classSolution {
public:staticvoid printDivisorsPairs(int n) {
int r = (int) std::floor(std::sqrt(n));
for (int i =1; i <= r; ++i) {
if (n % i ==0) {
if (n / i == i) std::printf("%d ", i);
else std::printf("%d %d ", i, n / i);
}
}
}
};
classSolution {
publicstaticvoidprintDivisorsPairs(int n) {
int r = (int)Math.floor(Math.sqrt(n));
for (int i = 1; i <= r; ++i) {
if (n % i == 0) {
if (n / i == i) System.out.printf("%d ", i);
else System.out.printf("%d %d ", i, n / i);
}
}
}
}
1
2
3
4
5
6
7
8
9
10
objectSolution {
funprintDivisorsPairs(n: Int) {
val r = kotlin.math.sqrt(n.toDouble()).toInt()
for (i in1..r) {
if (n % i ==0) {
if (n / i == i) print("$i ") else print("$i${n / i} ")
}
}
}
}
1
2
3
4
5
6
7
8
9
classSolution:
defprint_divisors_pairs(self, n: int) ->None:
r = int(n**0.5)
for i in range(1, r+1):
if n % i ==0:
if n // i == i:
print(i, end=' ')
else:
print(i, n//i, end=' ')
1
2
3
4
5
6
7
8
9
10
11
pubstructSolution;
impl Solution {
pubfnprint_divisors_pairs(n: i64) {
let r = (n asf64).sqrt().floor() asi64;
for i in1..=r {
if n % i ==0 {
if n / i == i { print!("{} ", i); } else { print!("{}{} ", i, n / i); }
}
}
}
}
Collect the small divisors while iterating up to sqrt(n) and save their large counterparts; then print small divisors followed by the reversed list of large divisors to produce a sorted sequence.
import java.util.*;
classSolution {
publicstaticvoidprintDivisorsSorted(int n) {
List<Integer> highs =new ArrayList<>();
int r = (int)Math.floor(Math.sqrt(n));
for (int i = 1; i <= r; ++i) {
if (n % i == 0) {
if (n / i == i) System.out.printf("%d ", i);
else { System.out.printf("%d ", i); highs.add(n / i); }
}
}
for (int i = highs.size() - 1; i >= 0; --i) System.out.printf("%d ", highs.get(i));
}
}
1
2
3
4
5
6
7
8
9
10
11
12
objectSolution {
funprintDivisorsSorted(n: Int) {
val highs = mutableListOf<Int>()
val r = kotlin.math.sqrt(n.toDouble()).toInt()
for (i in1..r) {
if (n % i ==0) {
if (n / i == i) print("$i ") else { print("$i "); highs.add(n / i) }
}
}
for (i in highs.size - 1 downTo 0) print("${highs[i]} ")
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
defprint_divisors_sorted(self, n: int) ->None:
highs = []
r = int(n**0.5)
for i in range(1, r+1):
if n % i ==0:
if n // i == i:
print(i, end=' ')
else:
print(i, end=' ')
highs.append(n//i)
for x in reversed(highs): print(x, end=' ')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
pubstructSolution;
impl Solution {
pubfnprint_divisors_sorted(n: i64) {
letmut highs: Vec<i64>= Vec::new();
let r = (n asf64).sqrt().floor() asi64;
for i in1..=r {
if n % i ==0 {
if n / i == i { print!("{} ", i); }
else { print!("{} ", i); highs.push(n / i); }
}
}
for&x in highs.iter().rev() { print!("{} ", x); }
}
}