The Fibonacci sequence is defined as = + where = 1 and = 1 are the seeds.
For a given prime number p, consider a new sequence which is (Fibonacci sequence) mod p. For example for p = 5, the new sequence would be 1, 1, 2, 3, 0, 3, 3, 1, 4, 0, 4, 4 …
The minimal zero of the new sequence is defined as the first Fibonacci number that is a multiple of p or mod p = 0.
Given prime no p, find the minimal zero of the sequence Fibonacci modulo p.
Input : 5 Output : 5 The fifth Fibonacci no (1 1 2 3 5) is divisible by 5 so 5 % 5 = 0. Input : 7 Output : 8 The 8th Fibonacci no (1 1 2 3 5 8 13 21) is divisible by 7 so 21 % 7 = 0.
A simple approach is to keep calculating Fibonacci numbers and for each of them calculate Fi mod p. However if we observe this new sequence, let denote the term of the sequence, then it follows : = ( + ) mod p. i.e. the remainder is actually the sum of remainders of previous two terms of this series. Therefore instead of generating the Fibonacci sequence and then taking modulo of each term we simply add previous two remainders and then take its modulo p.
Below is the implementation to find the minimal 0.
Minimal zero is: 8
This article is contributed by Aditi Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Fibonacci Number modulo M and Pisano Period
- Check if a M-th fibonacci number divides N-th fibonacci number
- Check if sum of Fibonacci elements in an Array is a Fibonacci number or not
- Compute n! under modulo p
- Chinese Remainder Theorem | Set 2 (Inverse Modulo based Implementation)
- Euler's criterion (Check if square root under modulo p exists)
- Find Square Root under Modulo p | Set 1 (When p is in form of 4*i + 3)
- Find Square Root under Modulo p | Set 2 (Shanks Tonelli algorithm)
- Cyclic Redundancy Check and Modulo-2 Division
- Find sum of modulo K of first N natural number
- Primitive root of a prime number n modulo n
- Maximum subarray sum modulo m
- Modulo 10^9+7 (1000000007)
- Multiply large integers under large modulo
- Program to find remainder without using modulo or % operator
- Maximum modulo of all the pairs of array where arr[i] >= arr[j]
- Discrete logarithm (Find an integer k such that a^k is congruent modulo b)
- Exponential Squaring (Fast Modulo Multiplication)
- Equalizing array using increment under modulo 3
- Divisibility by 3 where each digit is the sum of all prefix digits modulo 10