-
Notifications
You must be signed in to change notification settings - Fork 157
Expand file tree
/
Copy pathCountFactors.java
More file actions
30 lines (23 loc) · 798 Bytes
/
CountFactors.java
File metadata and controls
30 lines (23 loc) · 798 Bytes
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
package CountFactors;
class Solution {
public int solution(int N) {
// main idea:
// check from 1 to "sqrt_of_N"
// then, taking its pair into consideration
// ---> numFactor = numFactor * 2;
int sqrtN = (int) Math.sqrt(N);
int numFactor =0; // number of factors
// check if i is a factor or not (by using N % i ==0)
for(int i=1; i <= sqrtN; i++){
if(N % i ==0){
numFactor++;
}
}
numFactor = numFactor * 2; // add its pair
// be careful: check if "sqrtN * sqrtN == N"
if( sqrtN * sqrtN == N){
numFactor = numFactor -1; // minus one: avoid double counting
}
return numFactor;
}
}