오늘의 코딩 테스트

오늘의 코딩 테스트(약수의 개수)

oceanflow 2025. 2. 24. 10:53

두 정수 left와 right가 매개변수로 주어집니다. left부터 right까지의 모든 수들 중에서, 약수의 개수가 짝수인 수는 더하고, 약수의 개수가 홀수인 수는 뺀 수를 return 하도록 solution 함수를 완성하라

 

 

 

내가 푼 풀이

class Solution {
    public int solution(int left, int right) {
        int answer = 0;
        
        for (int i = left; i <= right; i++) {
            int count = 0;
            
            for (int j = 1; j <= i; j++) {
                if (i % j == 0)
                    count++;
            }
            
            if (count % 2 == 0){
                answer += i;
            } else {
                answer -= i;
            }
        }
        
        return answer;
    }
}

 

첫 풀이는 이렇게 풀었다.

for문을 돌려 left부터 right까지 count 즉, 약수의 개수를 구하기 위하여 for문안에 for문을 돌려 j가 1부터 i까지 i를 j로 나눈 나머지가 0인(약수)를 count에 누적 시켜 약수를 구하였다. 그리고 if문을 통해 약수 갯수에 따라 더하거나 빼주었다.

 

 

 

다른 풀이

 

IntStream 사용

import java.util.stream.IntStream;

class Solution {
    public int solution(int left, int right) {
        return IntStream.rangeClosed(left, right)
                       .map(i -> {
                           int count = (int) IntStream.rangeClosed(1, i)
                                                    .filter(j -> i % j == 0)
                                                    .count();
                           return count % 2 == 0 ? i : -i;
                       })
                       .sum();
    }
}

 

IntStream.rangeClosed(left, right) : left부터 right까지의 숫자 스트림 생성

int count = (int) IntStream.rangeClosed(1, i) : 1부터 i까지의 스트림 생성

 

filter(j -> i % j == 0) : i의 약수만 필터링

count() : 약수의 개수 계산

return count % 2 == 0 ? i : -i : 약수의 개수가 짝수면 양수, 홀수면 음수 반환

sum() : 최종 결과 합산

 

 

제곱수(sqrt) 활용

class Solution {
    public int solution(int left, int right) {
        int answer = 0;

        for (int i=left;i<=right;i++) {
            //제곱수인 경우 약수의 개수가 홀수
            if (i % Math.sqrt(i) == 0) {
                answer -= i;
            }
            //제곱수가 아닌 경우 약수의 개수가 짝수
            else {
                answer += i;
            }
        }

        return answer;
    }
}

 

이 풀이는 제곱수일 경우 약수의 개수가 항상 홀수인 수학적 성질을 활용한 풀이이다.

제곱수가 아닌 수는 약수의 개수가 항상 짝수이다.

 

이 풀이도 IntStream으로 구현할 수 있다.