Given an array of infinite length and two integers M and N which are co-primes, the task is to find the number of positions that cannot be visited starting from the first position when in a single move from arr[i], either arr[i + M] or arr[i + N] can be reached. Note that the result is always finite.
Input: M = 2, N = 5
From index 0, the indices that can be visited are
0 + 2 = 2
0 + 2 + 2 = 4
0 + 5 = 5
0 + 2 + 2 + 2 = 6
0 + 2 + 5 = 7
0 + 2 + 2 + 2 + 2 = 8
0 + 2 + 2 + 5 = 9
0 + 5 + 5 = 10
1 and 3 are the only indices that cannot be visited.
Input: M = 5, N = 6
- Find the largest index that can’t be obtained using any combination of M & N using Frobenius number say X = (M * N) – M – N .
- Since, X is the largest index than cannot be visited so every index greater than it doesn’t need to be checked.
- Now, for the indices smaller than X, if X is unvisited then Y = X – M and Z = X – N are also unrechable and same goes Y – M and Z – N and so on.. until the indices are greater than 0.
Below is the implementation of the above approach:
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.
- Find the index of first 1 in an infinite sorted array of 0s and 1s
- Count of indices in an array that satisfy the given condition
- Count the pairs in an array such that the difference between them and their indices is equal
- Find all good indices in the given Array
- Find indices of all local maxima and local minima in an Array
- Find the sum of infinite series 1^2.x^0 + 2^2.x^1 + 3^2.x^2 + 4^2.x^3 +.......
- Find if the given number is present in the infinite sequence or not
- Find minimum moves to reach target on an infinite line
- Count triplet of indices (i, j, k) such that XOR of elements between [i, j) equals [j, k]
- Magical Indices in an array
- Find the GCD of N Fibonacci Numbers with given Indices
- Find a permutation such that number of indices for which gcd(p[i], i) > 1 is exactly K
- Sum of all the Composite Numbers from Odd indices of the given array
- Recursive program to find all Indices of a Number
- Check if the array can be sorted using swaps between given indices only
- Reorder an Array according to given indices with repetition allowed
- Reverse the substrings of the given String according to the given Array of indices
- Find the count of even odd pairs in a given Array
- Range sum queries for anticlockwise rotations of Array by K indices
- Find Surpasser Count of each element in array
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.