본문 바로가기

IT/알고리즘

[코딜리티] - Lesson 10.CountFactors


안녕하세요 남갯입니다.






    public int solution(int N) {
// write your code in Java SE 8
int result = 1;
Map<Integer, Integer> hashMap = new HashMap<>();
int count = 0;
int beforeDiv = 2;
int div = 2;
while (N > 1) {
if (N % div == 0) {
N /= div;
hashMap.put(div, hashMap.getOrDefault(div, 0) + 1);
//다시 초기화 할필요가 없다
// div = 2;
} else {
div++;
}
}
Iterator iterator = hashMap.keySet().iterator();
while (iterator.hasNext()){
result *= (hashMap.get(iterator.next()) + 1);
}
return result;
}


https://app.codility.com/demo/results/training9ACB57-DUD/






    public int solution(int N) {
// write your code in Java SE 8
int result = 1;
Map<Integer, Integer> hashMap = new HashMap<>();
int count = 0;
int beforeDiv = 2;
int div = 2;
while (N > 1) {
if (N % div == 0) {
N /= div;
hashMap.put(div, hashMap.getOrDefault(div, 0) + 1);
//다시 초기화 할필요가 없다
count ++;
// div = 2;
} else {
if(count > 0){
result *= (count +1);
count = 0;
}
div++;
}
}
if(count > 0){
result *= (count +1);
}

return result;
}


https://app.codility.com/demo/results/training8BTMNQ-PGJ/


이래도 안되네...ㅋㅋㅋ



제곱근의 반이 정수일경우 2배 -1 아닐경우 2배



public int solution(int N) {
// write your code in Java SE 8
int result = 0;
//1..2..3..4..6..8..12..24
//즉 제곱근까지의 반까지 나눠지는 갯수 x 2 = 총 개수
double sqrt = Math.sqrt(N);
for (int i = 1; i <= sqrt; i++) {
if (N % i == 0) {
result++;
}
}
int checkint = (int) sqrt;
result *= 2;
if (sqrt == checkint) {
result--;
}

return result;
}


https://app.codility.com/demo/results/trainingMEYEQ3-CTH/