C++ countDivisors() 구현

1 개요[ | ]

C++ countDivisors() 구현
  • C++로 약수의 개수를 구하는 함수 구현

2 sqrt 사용[ | ]

#include <iostream>
#include <cmath>
using namespace std;

int countDivisors(int n) {
    int cnt = 0;
    for (int i = 1; i <= sqrt(n); i++) {
        if (n % i != 0) continue;
        if (n / i == i) cnt++;
        else cnt += 2;
    }
    return cnt;
}

int main() {
    cout << countDivisors(-1) << endl; // 0
    cout << countDivisors(0) << endl; // 0
    cout << countDivisors(1) << endl; // 1: 1
    cout << countDivisors(2) << endl; // 2: 1, 2
    cout << countDivisors(7) << endl; // 2: 1, 7
    cout << countDivisors(59) << endl; // 2: 1, 59
    cout << countDivisors(60) << endl; // 12: 1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30, 60
}

3 * 사용[ | ]

#include <iostream>
using namespace std;

int countDivisors(int n) {
    int cnt = 0;
    for (int i = 1; i*i <= n; i++) {
        if (n % i) continue;
        if (i*i == n) cnt++;
        else cnt += 2;
    }
    return cnt;
}

int main() {
    cout << countDivisors(-1) << endl; // 0
    cout << countDivisors(0) << endl; // 0
    cout << countDivisors(1) << endl; // 1: 1
    cout << countDivisors(2) << endl; // 2: 1, 2
    cout << countDivisors(7) << endl; // 2: 1, 7
    cout << countDivisors(59) << endl; // 2: 1, 59
    cout << countDivisors(60) << endl; // 12: 1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30, 60
}

4 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}