As a single operation between two positive integers we understand
multiplying one of the numbers by some prime number or dividing it by
such (provided it can be divided by this prime number without
the remainder). The distance between a and b denoted as d(a,b) is a
minimal amount of operations needed to transform number a into number
b. For example, d(69,42)=3.Keep in mind that our function d indeed has characteristics of the
distance – for any positive ints a, b and c we get:a) d(a,a)==0
b) d(a,b)==d(b,a)
c) the inequality of a triangle d(a,b)+d(b,c)>=d(a,c) is fulfilled.
You’ll be given a sequence of positive ints a_1, a_2,…,a_n. For every a_i of them
output such a_j (j!=i) that d(a_i, a_j) is as low as possible. For example, the sequence of length 6: {1,2,3,4,5,6} should output {2,1,1,2,1,2}.
This seems really hard to me. What I think would be useful is:
a) if a_i is prime, we are unable to make anything less than a_i (unless it’s 1) so the only operation allowed is multiplication. Therefore, if we have 1 in our set, for every prime number d(this_number, 1) is the lowest.
b) also, for 1 d(1, any_prime_number) is the lowest.
c) for a non-prime number we check if we have any of its factors in our set or multiplication of its factors
That’s all I can deduce, though. The worst part is I know it will take an eternity for such an algorithm to run and check all the possibilities… Could you please try to help me with it? How should this be done?
Indeed, you can represent any number
Nas 2^n1 * 3^n2 * 5^n3 * 7^n4 * … (most of the n’s are zeroes).This way you set a correspondence between a number
Nand infinite sequence (n1, n2, n3, …).Note that your operation is just adding or subtracting 1 at exactly one of the appropriate sequence’s places.
Let N and M be two numbers, and their sequences be (n1, n2, n3, …) and (m1, m2, m3, …).
The distance between the two numbers is indeed nothing but |n1 – m1| + |n2 – m2| + …
So, in order to find out the closest number, you need to calculate the sequences for all the input numbers (this is just decomposing them into primes). Having this decomposition, the calculation is straightforward.
Edit:
In fact, you don’t need the exact position of your prime factor: you just need to know, which is the exponent for each of the prime divisors.
Edit:
this is the simple procedure for converting the number into the chain representation:
Edit:
… and the code for distance: