Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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
Advertisements
