class Solution {
public int solution(int left, int right) {
int answer = 0;
//약수의 개수를 구해서 짝수면 +, 홀수면 - -> 그 값들을 전부 더함
int current = left;
while(current<=right){
int count = 0;
//약수 개수 구하기
for(int i=current;i>0;i--){
if(current%i == 0) count++;
}
//짝수면 answer+current, 홀수면 answer-current
if(count%2 == 0) answer += current;
else answer -= current;
current++;
}
return answer;
}
}
이렇게 직접 약수의 개수를 구해도 되지만, 우리가 원하는 것은 약수의 개수가 홀수인지 짝수인지 임으로 제곱수로 판단을 하면 된다.
제곱수면 약수의 개수가 홀수, 아니면 짝수이다. Math.sqrt()를 활용해서 제곱수인지 판단을 한다
for (int i=left;i<=right;i++) {
//제곱수인 경우 약수의 개수가 홀수
if (i % Math.sqrt(i) == 0) {
answer -= i;
}
//제곱수가 아닌 경우 약수의 개수가 짝수
else {
answer += i;
}
}