# Program to find nth term of a sequence which are divisible by a, b, c in Python

Suppose we have four numbers n, a, b, and c. We have to find the nth (0 indexed) term of the sorted sequence of numbers divisible by a, b or c.

So, if the input is like n = 8 a = 3 b = 7 c = 9, then the output will be 18, as The first 9 terms of the sequence are [1, 3, 6, 7, 9, 12, 14, 15, 18].

To solve this, we will follow these steps −

• if minimum of a, b, c is same as 1, then
• return n
• ab := lcm(a, b), bc := lcm(b, c), ca := lcm(a, c)
• abc := lcm(ab, c)
• left := 1, right := 10^9
• while left <= right, do
• mid :=(left + right) / 2
• na := quotient of mid / a
• nb := quotient of mid / b
• nc := quotient of mid / c
• nab := quotient of mid / ab
• nbc := quotient of mid / bc
• nca := quotient of mid / ca
• nabc := quotient of mid / abc
• numterms := na + nb + nc - nab - nbc - nca + nabc
• if numterms > n, then
• right := mid - 1
• otherwise when numterms < n, then
• left := mid + 1
• otherwise,
• return mid - minimum of (mid mod a, mid mod b, mid mod c)
• return -1

## Example (Python)

Let us see the following implementation to get better understanding −

import math
def lcm(a, b):
return (a * b) // math.gcd(a, b)
class Solution:
def solve(self, n, a, b, c):
if min(a, b, c) == 1:
return n
ab, bc, ca = lcm(a, b), lcm(b, c), lcm(a, c)
abc = lcm(ab, c)
left, right = 1, 10 ** 9
while left <= right:
mid = (left + right) // 2
na = mid // a
nb = mid // b
nc = mid // c
nab = mid // ab
nbc = mid // bc
nca = mid // ca
nabc = mid // abc
numterms = na + nb + nc - nab - nbc - nca + nabc
if numterms > n:
right = mid - 1
elif numterms < n:
left = mid + 1
else:
return mid - min(mid % a, mid % b, mid % c)
return -1
ob = Solution()
n = 8
a = 3
b = 7
c = 9
print(ob.solve(n, a, b, c))

## Input

8, 3, 7, 9

## Output

18

Updated on: 12-Dec-2020

171 Views