Techieindoor

Leetcode 2427: Number of Common Factors Solution

Here, we will see how to solve Number of Common Factors Solution of leet code 2427 problem.

You are given two positive integers a and b. You have to return the number of common factors of a and b.

An integer x is a common factor of a and b if x divides both a and b.

Example 1:

Input: a = 12, b = 6
Output: 4
Explanation: The common factors of 12 and 6 are 1, 2, 3, 6.

Example 2:

Input: a = 25, b = 30
Output: 2
Explanation: The common factors of 25 and 30 are 1, 5.

Example 3:

Input: a = 10, b = 5
Output: 2
Explanation: The common factors of 10 and 5 are 2.

Number of Common Factors Solution in C++:

Here, we will be solving problem in multiple ways with code.

C++ code 1:

class Solution {
public:
    int commonFactors(int a, int b) {
        int n = a > b ? a : b;
        int count = 1;
        
        for(int i = 2; i <= n; i++) {
            if(((a % i) == 0) && ((b % i) == 0)) {
                count++;
            }
        }
        return count;
    }
};

Output:

Input: a = 10, b = 5
Output: 2

Time complexity: O(n)

Space complexity: O(1)

To check more leetcode problem’s solution. Pls click given below link:

https://www.techieindoor.com/category/leetcode/

https://www.techieindoor.com/category/leetcode/

Exit mobile version