[Codility]Lesson10/Prime and Composite Numbers/CountFactors

Mijeong Ryu·2023년 5월 27일
0

Codility

목록 보기
4/17

https://app.codility.com/demo/results/trainingTNPDKU-EQB/

문제

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

코드

// you can also use imports, for example:

// import java.util.*;

// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");
import java.util.*;
class Solution {
    public int solution(int N) {
        int ans = 0;
        if(N==1){return 1;}
        for(long i=1; i*i<=N; i++){
            if(i*i==N){
                ans ++;
            }
            else if(N%i==0){
                ans +=2;
            }
        }
        return ans;
        // Implement your solution here
    }
}

풀이

단순히 약수의 수를 반환하는 문제인데,
반복문을 모두 돌면 시간복잡도 문제가 발생하여
i*i<=N 까지로 범위를 효율적으로 설정해주는 것과,
반복문에서 범위를 고려하여 INT대신 LONG으로 설정해주어야함

0개의 댓글