37
37
38
38
<!-- 这里可写通用的实现逻辑 -->
39
39
40
+ ** 方法一:枚举**
41
+
42
+ 一个数 $n$ 一定有 $1$ 和 $n$ 两个正除数,因此只需要枚举 $2$ 到 $n-1$ 之间的数,看它们是否是 $n$ 的正除数即可,是则累加计数器,最后判断计数器是否为 $1$ 即可。
43
+
44
+ 时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为给定的整数。
45
+
46
+ ** 方法二:枚举优化**
47
+
48
+ 我们可以枚举 $1$ 到 $\sqrt{n}$ 之间的数 $i$,如果 $n$ 能被 $i$ 整除,并且 $\frac{n}{i}$ 不等于 $i$,那么计数器累加 $2$,否则计数器累加 $1$。最后判断计数器是否为 $3$ 即可。
49
+
50
+ 时间复杂度 $O(\sqrt{n})$,空间复杂度 $O(1)$。其中 $n$ 为给定的整数。
51
+
40
52
<!-- tabs:start -->
41
53
42
54
### ** Python3**
@@ -49,6 +61,18 @@ class Solution:
49
61
return sum (n % i == 0 for i in range (2 , n)) == 1
50
62
```
51
63
64
+ ``` python
65
+ class Solution :
66
+ def isThree (self , n : int ) -> bool :
67
+ cnt = 0
68
+ i = 1
69
+ while i <= n // i:
70
+ if n % i == 0 :
71
+ cnt += 1 if i == n // i else 2
72
+ i += 1
73
+ return cnt == 3
74
+ ```
75
+
52
76
### ** Java**
53
77
54
78
<!-- 这里可写当前语言的特殊实现逻辑 -->
@@ -67,20 +91,50 @@ class Solution {
67
91
}
68
92
```
69
93
94
+ ``` java
95
+ class Solution {
96
+ public boolean isThree (int n ) {
97
+ int cnt = 0 ;
98
+ for (int i = 1 ; i <= n / i; ++ i) {
99
+ if (n % i == 0 ) {
100
+ cnt += n / i == i ? 1 : 2 ;
101
+ }
102
+ }
103
+ return cnt == 3 ;
104
+ }
105
+ }
106
+ ```
107
+
70
108
### ** C++**
71
109
72
110
``` cpp
73
111
class Solution {
74
112
public:
75
113
bool isThree(int n) {
76
114
int cnt = 0;
77
- for (int i = 2; i < n; ++i)
115
+ for (int i = 2; i < n; ++i) {
78
116
cnt += n % i == 0;
117
+ }
79
118
return cnt == 1;
80
119
}
81
120
};
82
121
```
83
122
123
+ ```cpp
124
+ class Solution {
125
+ public:
126
+ bool isThree(int n) {
127
+ int cnt = 0;
128
+ for (int i = 1; i <= n / i; ++i) {
129
+ if (n % i == 0) {
130
+ cnt += n / i == i ? 1 : 2;
131
+ }
132
+ }
133
+ return cnt == 3;
134
+ }
135
+ };
136
+ ```
137
+
84
138
### ** Go**
85
139
86
140
``` go
@@ -95,6 +149,22 @@ func isThree(n int) bool {
95
149
}
96
150
```
97
151
152
+ ``` go
153
+ func isThree (n int ) bool {
154
+ cnt := 0
155
+ for i := 1 ; i <= n/i; i++ {
156
+ if n%i == 0 {
157
+ if n/i == i {
158
+ cnt++
159
+ } else {
160
+ cnt += 2
161
+ }
162
+ }
163
+ }
164
+ return cnt == 3
165
+ }
166
+ ```
167
+
98
168
### ** JavaScript**
99
169
100
170
``` js
@@ -113,6 +183,22 @@ var isThree = function (n) {
113
183
};
114
184
```
115
185
186
+ ``` js
187
+ /**
188
+ * @param {number} n
189
+ * @return {boolean}
190
+ */
191
+ var isThree = function (n ) {
192
+ let cnt = 0 ;
193
+ for (let i = 1 ; i <= n / i; ++ i) {
194
+ if (n % i == 0 ) {
195
+ cnt += ~~ (n / i) == i ? 1 : 2 ;
196
+ }
197
+ }
198
+ return cnt == 3 ;
199
+ };
200
+ ```
201
+
116
202
### ** ...**
117
203
118
204
```
0 commit comments