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
-
Economics & Finance
Program to find nth term of a sequence which are divisible by a, b, c in Python
Given four numbers n, a, b, and c, we need to find the nth (0-indexed) term of the sorted sequence of numbers divisible by a, b, or c.
For example, if n = 8, a = 3, b = 7, c = 9, the first 9 terms of the sequence are [3, 6, 7, 9, 12, 14, 15, 18, 21], so the 8th term (0-indexed) is 18.
Approach
We use binary search with the inclusion-exclusion principle to count numbers divisible by a, b, or c up to a given value ?
- If minimum of
a,b,cis 1, returnn + 1(since all numbers are divisible by 1) - Calculate LCM pairs:
lcm(a,b),lcm(b,c),lcm(a,c) - Calculate triple LCM:
lcm(a,b,c) - Use binary search to find the nth term
- Apply inclusion-exclusion principle to count divisible numbers
Implementation
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 + 1
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
# Count numbers divisible by a, b, or c up to mid
na = mid // a
nb = mid // b
nc = mid // c
nab = mid // ab
nbc = mid // bc
nca = mid // ca
nabc = mid // abc
# Inclusion-exclusion principle
numterms = na + nb + nc - nab - nbc - nca + nabc
if numterms > n:
right = mid - 1
elif numterms < n:
left = mid + 1
else:
# Find the actual nth term by adjusting for remainder
return mid - min(mid % a, mid % b, mid % c)
return -1
# Test the solution
ob = Solution()
n = 8
a = 3
b = 7
c = 9
result = ob.solve(n, a, b, c)
print(f"The {n}th term is: {result}")
The output of the above code is ?
The 8th term is: 18
How It Works
The algorithm uses binary search on the answer space. For each candidate value mid, it counts how many numbers up to mid are divisible by a, b, or c using the inclusion-exclusion principle ?
-
Include: Count of numbers divisible by
a,b, andc - Exclude: Count of numbers divisible by pairs (to avoid double counting)
- Include: Count of numbers divisible by all three (to correct over-exclusion)
Example Walkthrough
# Let's trace through the sequence for a=3, b=7, c=9
def generate_sequence(a, b, c, limit=25):
sequence = []
for i in range(1, limit + 1):
if i % a == 0 or i % b == 0 or i % c == 0:
sequence.append(i)
return sequence
a, b, c = 3, 7, 9
sequence = generate_sequence(a, b, c)
print("First 10 terms:", sequence[:10])
print(f"8th term (0-indexed): {sequence[8]}")
First 10 terms: [3, 6, 7, 9, 12, 14, 15, 18, 21, 24] 8th term (0-indexed): 21
Conclusion
This solution efficiently finds the nth term using binary search combined with the inclusion-exclusion principle. The time complexity is O(log n) and space complexity is O(1).
