Codility_CountFactors

functionMan·2024년 8월 29일

Codility

목록 보기
28/32
post-thumbnail

10-1. CountFactors

A positive integer D is a factor of a positive integer N if there exists an integer M such that N = D * M.

For example, 6 is a factor of 24, because M = 4 satisfies the above condition (24 = 6 * 4).

Write a function:

class Solution { public int solution(int N); }

that, given a positive integer N, returns the number of its factors.

For example, given N = 24, the function should return 8, because 24 has 8 factors, namely 1, 2, 3, 4, 6, 8, 12, 24. There are no other factors of 24.

Write an efficient algorithm for the following assumptions:

N is an integer within the range [1..2,147,483,647].

양의 정수 D는 양의 정수 N의 인수입니다. 만약 정수 M이 존재하여 N = D * M을 만족한다면, D는 N의 인수입니다.

예를 들어, 6은 24의 인수입니다. 왜냐하면 M = 4가 위의 조건을 만족하기 때문입니다 (24 = 6 * 4).

다음과 같은 함수를 작성하세요:

class Solution { 
    public int solution(int N); 
}

이 함수는 양의 정수 N이 주어졌을 때, N의 인수의 수를 반환해야 합니다.

예를 들어, N = 24가 주어지면, 함수는 8을 반환해야 합니다. 왜냐하면 24는 8개의 인수(1, 2, 3, 4, 6, 8, 12, 24)를 가지고 있기 때문입니다. 24의 다른 인수는 없습니다.

다음 가정을 위한 효율적인 알고리즘을 작성하세요:

N은 [1…2,147,483,647] 범위 내의 정수입니다.

문제풀이

import java.util.*;

class Solution {
    public int solution(int N) {
        int count = 0;
        if(N == 0){
            return 0;
        }
        for(int i = 1; i <= N; i++){
         if(N % i == 0){
             count++;
         }   
        }
        return count;
    }
}

해당 코드로 제출 시 큰수에서 타임아웃 발생

수정 ->

import java.util.*;

class Solution {
    public int solution(int N) {
        if (N == 0) {
            return 0;
        }
        int count = 0;
        for (int i = 1; i * i <= N; i++) {
            if (N % i == 0) {
                count++;
                if (i != N / i) {
                    count++;
                }
            }
        }
        return count;
    }
}

36의 약수는 1, 2, 3, 4, 6, 9, 12, 18, 36으로 총 9개입니다.
위 규칙에서 136 = 36, 2 18 = 36, 3 * 12 = 36 이런식으로 규칙을 볼 수 있습니다.

반복문의 예시를 보면
i = 1: 36 % 1 == 0이므로 count++ (count = 1), 1 != 36 / 1이므로 count++ (count = 2)

i = 2: 36 % 2 == 0이므로 count++ (count = 3), 2 != 36 / 2이므로 count++ (count = 4)

i = 3: 36 % 3 == 0이므로 count++ (count = 5), 3 != 36 / 3이므로 count++ (count = 6)

i = 4: 36 % 4 == 0이므로 count++ (count = 7), 4 != 36 / 4이므로 count++ (count = 8)

i = 5: 36 % 5 != 0이므로 count 하지 않음

i = 6: 36 % 6 == 0이므로 count++ (count = 9), 6 == 36 / 6이므로 count 하지 않음

이런식으로 i * i <= N의 범위 지정을 통해 반복문의 반복횟수를 줄여 시간을 단축하고
중복 조건을 제외하고 ex)'6' 카운팅하여 값을 구할 수 있습니다.

제출결과

아직 92% 성능으로 개선이 필요합니다..

문제풀어보기 -> https://app.codility.com/programmers/lessons/10-prime_and_composite_numbers/count_factors/

profile
functionMan

0개의 댓글