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.
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:
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:
def gcd(a, b):
while b:
a, b = b, a %b
return a
And it can be done Recursively:
def gcd(a, b):
if b:
return gcd(b, a % b)
return a
The time complexity of GCD algorithm is
–EOF (The Ultimate Computing & Technology Blog) —
Last Post: Teaching Kids Programming - Maximum Ascending Subarray Sum (Greedy Algorithm)
Next Post: C#: How to Create, Update, Delete and Check (If Exists) an Azure Resource Group in .NET?