-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathFactors.java
More file actions
52 lines (44 loc) · 1.23 KB
/
Factors.java
File metadata and controls
52 lines (44 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package Math;
import java.util.ArrayList;
public class Factors {
public static void main(String[] args) {
factor3(20);
}
// O(n)
static void factor1(int n){
for(int i=1; i<=n; i++){
if(n%i==0){
System.out.print(i + " ");
}
}
}
// O(sqrt(n))
static void factor2(int n){
for(int i = 1; i <= Math.sqrt(n); i++){
if(n%i == 0){
if(n/i == i){
System.out.print(i + " ");
}else{
System.out.print(i + " " + n/i + " ");
}
}
}
}
// both time and space with be O(sqrt(n))
static void factor3(int n) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 1; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
if (n/i == i) {
System.out.print(i + " ");
}else {
System.out.print(i + " ");
list.add(n/i);
}
}
}
for (int i = list.size() - 1; i >= 0; i--) {
System.out.print(list.get(i) + " ");
}
}
}