# Teaching Kids Programming – Number of Common Factors (Brute Force Algorithm + Greatest Common Divisor)

Teaching Kids Programming – Number of Common Factors (Brute Force Algorithm + Greatest Common Divisor) | ninjasquad

Teaching Kids Programming: Videos on Data Structures and Algorithms

Given two positive integers a and b, 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.

Constraints:
1 <= a, b <= 1000

### Number of Common Factors (Bruteforce Algorithm + Greatest Common Divisor)

We can bruteforce the numbers from 2 (inclusive) to the GCD (Greatest Common Divisor) between two numbers.

 ```1 2 3 4 5 6 7 8 ``` ```class Solution:     def commonFactors(self, a: int, b: int) -> int:         x = gcd(a, b)         ans = 1         for i in range(2, x + 1):             if x % i == 0:                 ans += 1         return ans```
```class Solution:
def commonFactors(self, a: int, b: int) -> int:
x = gcd(a, b)
ans = 1
for i in range(2, x + 1):
if x % i == 0:
ans += 1
return ans```

And this can be written using one-liner:

 ```1 ``` `return sum(1 for i in range(1, x + 1) if x % i == 0)`
`return sum(1 for i in range(1, x + 1) if x % i == 0)`

The GCD Algorithm (Teaching Kids Programming – Algorithms of Greatest Common Divisor and Least Common Multiples) of two integers:

 ```1 2 3 4 ``` ```def gcd(a, b):   while b:     a, b = b, a %b   return a```
```def gcd(a, b):
while b:
a, b = b, a %b
return a```

And it can be done Recursively:

 ```1 2 3 4 ``` ```def gcd(a, b):   if b:     return gcd(b, a % b)   return a```
```def gcd(a, b):
if b:
return gcd(b, a % b)
return a```

The time complexity of GCD algorithm is $tex_77988249062c78cf62a5f522b3ef49ef Teaching Kids Programming - Number of Common Factors (Brute Force Algorithm + Greatest Common Divisor) algorithms math python Recursion teaching kids programming youtube video$

GD Star Rating