Similar Problems

Similar Problems not available

Number Of Common Factors - Leetcode Solution

Companies:

LeetCode:  Number Of Common Factors Leetcode Solution

Difficulty: Easy

Topics: math  

The Problem:

Given two integers a and b, you have to calculate the number of common factors of these two integers.

Solution:

The approach to solve the problem is as follows:

  1. Find the prime factorization of both the integers a and b.
  2. Count the number of occurrences of prime factors in both a and b.
  3. Multiply the counts for all the common prime factors.
  4. The product of the counts is the number of common factors.

Let's understand this approach with an example.

Suppose a = 60 and b = 24.

Step 1: Prime factorization of a 60 = 2 * 2 * 3 * 5

Prime factorization of b 24 = 2 * 2 * 2 * 3

Step 2: Count the occurrences of prime factors

For a, 2 occurs 2 times 3 occurs 1 time 5 occurs 1 time

For b, 2 occurs 3 times 3 occurs 1 time

Step 3: Count the common prime factors

Common factors are 2 and 3.

2 occurs 2 times in a and 3 times in b. 3 occurs 1 time in a and 1 time in b.

Step 4: Multiply the counts of common prime factors

The number of common factors is: 2^2 * 3^1 = 12

Therefore, the number of common factors of 60 and 24 is 12.

Implementation:

The above approach can be implemented in Python as follows:

def common_factors(a, b): factors = {} for i in range(2, max(a, b) + 1): while a % i == 0 or b % i == 0: factors[i] = factors.get(i, 0) + 1 if a % i == 0: a /= i if b % i == 0: b /= i product = 1 for factor, count in factors.items(): if count > 1: product *= count return product

In this function, we use a dictionary to store the factors and their counts, and a for loop to iterate over all the integers between 2 and the maximum of a and b. We check if either a or b is divisible by the current integer, and if so, increment the count of that factor in the dictionary. We then divide a and b by that factor to reduce complexity.

Finally, we use another for loop to iterate over the factors and their counts, and multiply the counts of factors that occur more than once to get the product of counts. We return this product as the number of common factors.

Time Complexity: O(max(a, b)) - We need to iterate over all the integers from 2 to max(a,b).

Number Of Common Factors Solution Code

1