Reputation: 59
Given an array of n numbers, replace each element with it’s farthest coprime in the range [2, 250]. Example, the farthest coprime for 2 is 249 and for 243 is 2.
Could anyone help me with algorithm with the best complexity yo solve this?
Upvotes: 0
Views: 7855
Reputation: 30926
As the number range is small I would go for some application of sieve.
for (int i = 2; i <= N; ++i)
{
if (N % i == 0)
{
sieve[i] = 1;
for (int j = 2; j * i <= 250; ++j)
{
sieve[i * j] = 1;
}
}
}
After that using this, you will look for smallest value sm
for which sieve[sm]
is 0 and also largest value lg
for which sieve[lg]
is 0.
Then among them get from which the distance to N
is maximum. That is your answer.
Sieve has the complexity of O(nloglogn)
. And the looping to find the farthest will be O(n)
. So overall complexity is O(nloglogn)
.
Simply we are marking the values that are not co-prime for this particular number N.
Then we just loop over to get the smallest and largest number which are coprime to the given number. We then calculate the distance and then make the largest one as the answer.
Upvotes: 2
Reputation: 7290
For the farthest coprime of N from the range [2, 250], the candidates are:
Of these (up to) three candidates, choose the one farthest from N.
Upvotes: 1