알고리즘 - 합성수 찾기 - 120846

워니·2023년 4월 3일

알고리즘

목록 보기
13/30
post-thumbnail

[level 0] 합성수 찾기 - 120846

문제 링크

성능 요약

메모리: 77 MB, 시간: 0.04 ms

구분

코딩테스트 연습 > 코딩테스트 입문

채점결과


정확성: 100.0
합계: 100.0 / 100.0

문제 설명

약수의 개수가 세 개 이상인 수를 합성수라고 합니다. 자연수 n이 매개변수로 주어질 때 n이하의 합성수의 개수를 return하도록 solution 함수를 완성해주세요.


제한사항
  • 1 ≤ n ≤ 100

입출력 예
n result
10 5
15 8

입출력 예 설명

입출력 예 #1

  • 10 이하 합성수는 4, 6, 8, 9, 10 로 5개입니다. 따라서 5를 return합니다.

입출력 예 #1

  • 15 이하 합성수는 4, 6, 8, 9, 10, 12, 14, 15 로 8개입니다. 따라서 8을 return합니다.

출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges


  • 내 풀이
class Solution {
    public int solution(int n) {
        int answer = 0;

        for (int i = 4; i <= n; i++) {
            int sqrt = (int) Math.sqrt(i);
            int temp = 0;
            int x = 1;
            while (x <= sqrt) {
                if (i % x == 0) {
                    temp++;
                    if (i / x != x) {
                        temp++;
                    }
                }
                x++;
            }
            if (temp >= 3) {
                answer++;
            }
        }
        return answer;
    }
}
  • TDD
class SolutionTest {

    @Test
    @DisplayName("N = 10 result = 5")
    void solution() {
        Assertions.assertThat(new Solution().solution(10)).isEqualTo(5);
    }

    @Test
    @DisplayName("N = 10 result = 5")
    void solution2() {
        Assertions.assertThat(new Solution().solution(15)).isEqualTo(8);
    }
}
profile
Backend-Dev

0개의 댓글