-2

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.

New contributor
ToridFartFart is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
6
  • You say, "And I need an algorithm which finds shortest use of f(x) trying to sort the sequence." Do you mean that function f is the key argument to be used with the built-in sort function and you need to create f? 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) and f(2) are both 1. Commented 10 hours ago
  • To clarify, is the array sorted or not? I don't think it matters, but maybe there could be an optimization. Second, you used the sieve once to find primes up to the largest integer, correct? Are there storage restrictions? Because when finding primes to the maximum integer just once could all be stored, and a lookup should be fast. Where is the speed bottleneck? Commented 10 hours ago
  • @Booboo Function f(x) is just my expression of what actions you can do while trying to make sorted sequence For example: You get sequence [10, 9, 6, 7, 7] so here the answer is 2. Because you can just change both 7 -> 5 and it will be sorted sequence [10, 9, 6, 5, 5] Commented 10 hours ago
  • @JohnBayko You won't get sorted array. That's exactly what I did. I just found the highest number, made the primes sequence and then use it for all sequences. It should be done in couple of seconds. Low sequences aren't hard to solve quickly but sequences where the highest number is 10^6 and there are 10^6 numbers are hardest cause you can't use brute force Commented 10 hours ago
  • You need to add example input and desired output. Commented 9 hours ago

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.