# L10-CountFactors ###### tags: `Codility_lessons` ## Question ## Key 1. for-loop外的變數可以用在loop中 2. 因數不會兩個都大於目標數的平方根,因此只要遍尋到目標數的平方根即可,不用遍尋N個數字 3. 每次會找到一組兩個因數,因此加二,而剛好是平方數的時候,則加一 ## Reference ## Solution ```cpp= int solution(int n) { if (n == 1) return 1; if (n == 2) return 2; int div = 2; // one and itself long x = 2; for (; x*x < n; x++) { if (n % x == 0) { div += 2; } } if (x * x == n) { div++; } return div; } ```