Nth multiple of a number in Fibonacci Series in Python
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, starting with 0 and 1:
0, 1, 1, 2, 3, 5, 8, 13, 21, ...
In this article, we will find the n-th Fibonacci number that is divisible by a given number m.
Example:
Input: n=2, m=3
Output: 21
Explanation: If n = 2 and m = 3, the Fibonacci numbers divisible by 3 (m) are 3, 21, 144, 987, ... Hence, the second multiple of 3 in the Fibonacci sequence is 21.
Iterative Approach
In this method, Fibonacci numbers are generated one by one in a loop. Each number is checked for divisibility by m, and a counter is increased until the n-th multiple is reached.
n, m = 4, 3
a, b, count = 0, 1, 0
while True:
a, b = b, a + b
if b % m == 0:
count += 1
if count == n:
print(b)
break
Output
987
Explanation:
- a, b = b, a + b: generates Fibonacci numbers iteratively.
- if b % m == 0: checks if current Fibonacci number is divisible by m.
- count: keeps track of how many multiples have been found.
- When count == n, the nth multiple is printed.
Dynamic Programming
This approach stores previously computed Fibonacci numbers in a list to avoid redundant calculations. It avoids recalculating Fibonacci numbers by storing them in a list, making it efficient for larger inputs.
def fun(n, m):
fib = [0, 1]
count = 0
while True:
fib.append(fib[-1] + fib[-2])
if fib[-1] % m == 0:
count += 1
if count == n:
return fib[-1]
n, m = 4, 3
print(fun(n, m))
Output
987
Explanation:
- fib.append(fib[-1] + fib[-2]): appends the next Fibonacci number.
- fib[-1] % m == 0: checks for divisibility.
- When count equals n, the function returns the required Fibonacci number.
Recursive Approach with Memoization
This method calculates Fibonacci numbers recursively while storing results in a dictionary to avoid redundant calculations.
def fib(n, memo={0: 0, 1: 1}):
if n not in memo:
memo[n] = fib(n - 1, memo) + fib(n - 2, memo)
return memo[n]
def fun(n, m):
count, idx = 0, 2
while True:
value = fib(idx)
if value % m == 0:
count += 1
if count == n:
return value
idx += 1
n, m = 4, 3
print(fun(n,m))
Output
987
Explanation:
- fib(n, memo): recursively calculates the nᵗʰ Fibonacci number using memoization for faster lookup.
- while loop: iterates through Fibonacci numbers starting from index 2.
- value % m == 0 (Divisibility check): increments a counter each time a Fibonacci number is divisible by m.