Data Structure & Algorithms
DSA
Introduction to problem solving
Count Factors

Count Factors

Problem Description

Given an integer A, you need to find the count of it's factors. Factor of a number is the number which divides it perfectly leaving no remainder. Example : 1, 2, 3, 6 are factors of 6

Problem Constraints

1 <= A <= 10^9

Input Format

First and only argument is an integer A.

Output Format

Return the count of factors of A.

Example Input

Input 1:
5

Input 2:
10

Example Output

Output 1:
2

Output 2:
4

Example Explanation

Explanation 1:
Factors of 5 are 1 and 5.

Explanation 2:
Factors of 10 are 1, 2, 5 and 10.

Output

Java
public class CountFactors {
    public int countFactors(int A) {
        int count = 0;
        for (int i = 1; i <= Math.sqrt(A); i++) {
            if (A % i == 0) {
                if (A / i == i) {
                    count++;
                } else {
                    count += 2;
                }
            }
        }
        return count;
    }
 
    public static void main(String[] args) {
        CountFactors solution = new CountFactors();
        int input1 = 5;
        int input2 = 10;
        System.out.println("Output 1: " + solution.countFactors(input1));
        System.out.println("Output 2: " + solution.countFactors(input2));
    }
}
 
Python
class Solution:
    def count_factors(self, A):
        count = 0
        i = 1
        while i * i <= A:
            if A % i == 0:
                if A / i == i:
                    count += 1
                else:
                    count += 2
            i += 1
        return count
 
solution = Solution()
input1 = 5
input2 = 10
print("Output 1:", solution.count_factors(input1))
print("Output 2:", solution.count_factors(input2))
JavaScript
function countFactors(A) {
    let count = 0;
    for (let i = 1; i <= Math.sqrt(A); i++) {
        if (A % i === 0) {
            if (A / i === i) {
                count++;
            } else {
                count += 2;
            }
        }
    }
    return count;
}
 
const input1 = 5;
const input2 = 10;
console.log("Output 1:", countFactors(input1));
console.log("Output 2:", countFactors(input2));