
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to count number of common divisors of two numbers in Python
Suppose we have two numbers a and b. We have to find how many positive integers are there, that are divisors to both a and b.
So, if the input is like a = 288 b = 240, then the output will be 10 because the common divisors are [1,2,3,4,6,8,12,16,24,48].
To solve this, we will follow these steps −
- res := 0
- for i in range 1 to gcd(a, b) + 1, do
- if (a mod i) is 0 and (b mod i) is 0, then
- res := res + 1
- if (a mod i) is 0 and (b mod i) is 0, then
- return res
Example
Let us see the following implementation to get better understanding −
from math import gcd def solve(a, b): res = 0 for i in range(1, gcd(a,b)+1): if (a % i) == 0 and (b % i) == 0: res += 1 return res a, b = 288, 240 print(solve(a, b))
Input
288, 240
Output
10
- Related Articles
- Python Program for Common Divisors of Two Numbers
- C++ Program for Common Divisors of Two Numbers?
- Java Program for Common Divisors of Two Numbers
- C++ Program for the Common Divisors of Two Numbers?
- Count the number of common divisors of the given strings in C++
- Program to find count of numbers having odd number of divisors in given range in C++
- Program to maximize number of nice divisors in Python
- Count common prime factors of two numbers in C++
- Program to count number of stepping numbers of n digits in python
- Check if sum of divisors of two numbers are same in Python
- Greatest common divisors in Python
- Count of common multiples of two numbers in a range in C++
- Count the numbers < N which have equal number of divisors as K in C++
- Program to count number of overlapping islands in two maps in Python
- Count all perfect divisors of a number in C++

Advertisements