Consider the following data:
arr = [2,3,5,7,11,13,17,19]
n = 100
Output of the given should be 0 since n % 2 = 0 and arr[0] = 2.
Since array is sorted I want to use that to my advantage and design an algorithm that can work in a complexity smaller than O(n), which you have by iterating over the whole array and finding first i such that n % arr[i] = 0.
I instantly thought of using modified Binary Search with the same complexity as the regular Binary Search(O(logN)), which does the same as a regular Binary Search which divides the search interval in half in each iteration with slight modification. Here is the implementation i used:
public int SmallestFactorIndex(int n)
{
int left = 0;
int right = max;
int index = -1;
while (left <= right)
{
int middle = (right - left) / 2 + left;
int middleValue = sieve[middle];
if (n % middleValue == 0)
{
index = middle;
right = middle - 1;
}
else if (middleValue < n)
{
left = middle + 1;
}
else
{
right = middle - 1;
}
}
return index;
}
Max represents length of the array - 1 and sieve is the sorted array of prime numbers. Only addition to the Binary Search is that if the current number does divide n, I dont instantly return that index but continue searching for a smaller number than that current number by moving the right border to the middle one. All other parts work pretty much the same way. I dont think I can take advantage of the fact that the array only consists of the prime numbers but I might be wrong.