2015年3月7日土曜日

Lesson 8: CountFactors (Count Factors)

Lesson 8: CountFactors
https://codility.com/programmers/lessons/8

This is a easy problem. As the factors are paired except when the factor is equal to sqrt(N), we only have to check from 1 to sort(N). When the value is a factor, then increment the counter by 2. Yet when sqrt(N) is also a factor, we shouldn't count it twice. So we decrement 1 before returning the answer.

This strategy gives the 100% score.









int solution(int N) {
    
    int cnt = 0;
    
    int i;
    double sqrtN = sqrt(N);
    
    for (i = 1; i <= sqrtN; i++){
        if (N % i == 0){
            cnt += 2;
        }
    }
    
    //to avoid the sqrt(N) to counted twice.
    if (sqrtN == (int)sqrtN){
        cnt--;
    }
    
    return cnt;
}

0 件のコメント:

コメントを投稿