Imagine you get sequence of integers:
[a1 a2 a3 ... an]
where:
1 <= a <= 10^6
1 <= n <= 10^6
You are given a function f(x) that can change a number to the closest lower prime number, or to 1 if there is no lower prime.
I need an algorithm that finds the shortest use of f(x) trying to sort the sequence, either in descending or ascending order.
I tried writing a program in Python that would first make a sequence of all prime numbers up to the highest number using the Sieve of Eratosthenes algorithm, and then loops through the numbers, lowering them accordingly. I'd try descending and ascending and then pick the lower number of operations. However, it was too slow.
fis the key argument to be used with the built-insortfunction and you need to createf? By the way, for all integers x in the range [3, 10**6] there is always some integer p such that p < x and p is prime.f(1)andf(2)are both 1.