본문 바로가기

Lesson 10. Prime and composite numbers - CountFactors #1

반응형

1. 문제

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:
  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].

 

약수의 갯수를 구하는 문제

예시) N = 24, return 8 (1, 2, 3, 4, 6, 8, 12, 24)

 

2. 매개변수 제한

  • 정수(N): 1 ~ 2,147,483,647

 

3. 코드 (C++)

1부터 N까지 나누어 떨어지는(나머지 0) 수를 찾는다

int solution(int N) {

    int cnt = 0;
    for(int i = 1; i <= N; i++)
    {
        if(N % i == 0) cnt++;
    }

    return cnt;
}

 

4. 결과

반응형