easy
0 views
Factor Count – CTS PATTERN
Count the number of positive divisors (factors) of a given integer.
Understand the Problem
Problem Statement
You are given an integer num. Your task is to determine how many positive integers divide num without leaving a remainder. This count is known as the factor count or divisor count of the number.
Function Signature:
int getFactorCount(int num)
The function accepts a single integer num as input and should return an integer representing the total number of its positive factors.
Constraints
- 1 ≤
num≤ 106 - The input
numis a positive integer.
Examples
Example 1
Input
12Output
6Explanation
The factors of 12 are 1, 2, 3, 4, 6, and 12. Therefore, the factor count is 6.
Example 2
Input
7Output
2Explanation
The factors of 7 are 1 and 7. Since 7 is a prime number, it has exactly 2 factors.
Example 3
Input
1Output
1Explanation
The only factor of 1 is 1 itself. Therefore, the factor count is 1.
Solution
#include <stdio.h>
int getFactorCount(int num){
int count = 0;
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
count++;
}
}
return count;
}
int main() {
int num;
scanf("%d", &num);
printf("%d\n", getFactorCount(num));
return 0;
}Time:O(n)
Space:O(1)
Approach:
C Implementation:
- Define the function
getFactorCountthat takes an integer parameternum. - Initialize a variable
countto 0 to keep track of the number of factors. - Use a
forloop to iterate from 1 tonum(inclusive). - Inside the loop, check if
numis divisible by the current iteratoriusing the modulo operator (%). - If the condition is true, increment the
count. - After the loop, return the final
count. - In the
mainfunction, read the input, callgetFactorCount, and print the result.
Time Complexity: O(n) Space Complexity: O(1)
Visual Explanation
Loading diagram...