Solve recurrence relation in which there is a separate relation for even and odd values - algorithm

Can someone help me how to solve these type of questions? What kind of approach should I follow?

Looking over the question, since you will be asked to
evaluate the recurrence lots of times
for very large inputs,
you will likely need to either
find a closed-form solution to the recurrence, or
find a way to evaluate the nth term of the recurrence in sublinear time.
The question, now, is how to do this. Let's take a look at the recurrence, which was defined as
f(1) = f(2) = 1,
f(n+2) = 3f(n) if n is odd, and
f(n+2) = 2f(n+1) - f(n) + 2 if n is even.
Let's start off by just exploring the recurrence to see if any patterns arise. Something that stands out here - the odd terms of this recurrence only depend on other odd terms in the recurrence. This means that we can imagine trying to split this recurrence into two smaller recurrences: one that purely deals with the odd terms, and one that purely deals with the even terms. Let's have D(n) be the sequence of the odd terms, and E(n) be the sequence of the even terms. Then we have
D(1) = 1
D(n+2) = 3D(n)
We only need to evaluate D on odd numbers, so we can play around with that to see if a pattern emerges:
D(2·0 + 1) = 1 = 30
D(2·1 + 1) = 3 = 31
D(2·2 + 1) = 9 = 32
D(2·3 + 1) = 27 = 33
The pattern here is that D(2n+1) = 3n. And hey, that's great news! That means that we have a direct way of computing D(2n+1).
With that in mind, notice that E(n) is defined as
E(2) = 1 = D(1)
E(n+2) = 2D(n+1) - E(n) + 2
Remember that we know the exact value of D(n+1), which is going to make our lives a lot easier. Let's see what happens if we iterate on this recurrence a bit. For example, notice that
E(8)
= 2D(7) - E(6) + 2
= 2D(7) + 2 - (2D(5) - E(4) + 2)
= 2D(7) - 2D(5) + E(4)
= 2D(7) - 2D(5) + (2D(3) - E(2) + 2)
= 2D(7) - 2D(5) + 2D(3) + 2 - D(1)
= 2D(7) - 2D(5) + 2D(3) - D(1) + 2
Okay... that's really, really interesting. It seems like we're getting an alternating sum of the D recurrence, where we alternate between including and excluding 2. At this point, if I had to make a guess, I'd say that the way to solve this recurrence is going to be to think about subdividing the even case further into cases where the inputs are 2n for an even n and 2n for an odd n. In fact, notice that if the input is 2n for even n, then there won't be a +2 term at the end (all the +2's are balanced out by -2's), whereas if the input is odd, then there will be a +2 term at the end (all the +2's are balanced out by -2's).
Now, let's turn to a different aspect of the problem. You weren't asked to query for individual terms of the recurrence. You were asked to query for the sum of the recurrence, evaluated over a range of inputs. The fact that we're getting alternating sums and differences of the D terms here is really, really interesting. For example, what is f(10) + f(11) + f(12)? Well, we know that f(11) = D(11), which we can compute directly. And we also know that f(10) and f(12) are E(10) and E(12). And watch what happens if we evalute E(10) + E(12):
E(10) + E(12)
= (D(9) - D(7) + D(5) - D(3) + D(1) + 2) + (D(11) - D(9) + D(7) - D(5) + D(3) - D(1))
= D(11) + (D(9) - D(9)) + (D(7) - D(7)) + (D(5) - D(5)) + (D(3) - D(3)) + (D(1) - D(1)) + 2
= D(11) + 2.
Now that's interesting. Notice that all of the terms have cancelled out except for the D(11) term and the +2 term! More generally, this might lead us to guess that there's some rule about how to simplify E(n+2) + E(n). In fact, there is. Specifically:
E(2n) + E(2n+2) = D(2n+1) + 2
This means that if we're summing up lots of consecutive values in a range, every pair of adjacent even terms will simplify instantly to something of the form D(2n+1) + 2.
There's still some more work to be done here. For example, you'll need to be able to sum up enormous numbers of D(n) terms, and you'll need to factor in the effects of all the +2 terms. I'll leave those to you to figure out.
One hint: all the values you're asked to return are modulo some number P. This means that the sequence of values 0, D(1), D(1) + D(3), D(1) + D(3) + D(5), D(1) + D(3) + D(5) + D(7), etc. eventually has to reach 0 again (mod P). You can both compute how many terms have to happen before this occurs and write down all the values encountered when doing this by just computing these values explicitly. That will enable you to sum up huge numbers of consecutive D terms in a row - you can mod the number of terms by the length of the cycle, then look up the residual sum in the table.
Hope this helps!

Related

Understanding a Particular Recursive Algorithm

Which problem does the algorithm Delta below solve, where m, n >= 0 are integers?
So Im finding the algorithm very hard break down due to the nature of the nested recursion and how it calls on another recursive algorithm. If I had to guess I would say that Delta solves the LCS(longest common subsequence) problem, but Im not able to give a good explanation as to why.
Could someone help me break down the algorithm and explain the recursion and how it works?
As you found out yourself, delta computes the product of two integers.
The recursion indeed makes this confusing to look at but the best way to gain intuition is to perform the computation by hand on some example data. But by looking at the functions separately, you will find that:
Gamma is just summation. Gamma(n,m) = gamma(n, m - 1) + 1 essentially performs a naive summation where you count down the second term, while adding 1 to the first. Example:
3 + 3 =
(3 + 2) + 1 =
((3 + 1) + 1) + 1 =
(((3 + 0) + 1) + 1) + 1 =
6
Knowing this, we can simplify Delta:
Delta(n, m) = n + Delta(n, m - 1) (if m!=0, else return 0).
In the same way, we are counting down on the second factor, but instead of adding 1, we add n. This is in indeed one definition of multiplication. It is easy to understand this if you manually solve an example just like above.

In which order the woman should bring the cats back in order to minimize the time?

A woman watches her cats leave one by one with different speeds in different directions. She took a motorcycle with one extra seat and follows the cats and picks up one cat at a time and brings them back home. Each cat moves with constant individual speed Vi and left home at time Ti. In which order the woman should bring the cats back in order to minimize the time?
I am trying to solve this problem but do not know how to begin.
Summary:
Sort the cats according to the metric v / x in descending order, where v is the cat's constant speed and x is the cat's initial displacement at time t = 0. It doesn't matter how you break ties. Once the order is initially established, it will remain the most efficient order in which to get cats as long as it is followed; so follow it.
Candidates debunked:
In both cases, allow the motorcycle speed to be w = 20.
It is proposed that you get cats in order from fastest to slowest. Counterexample: Cat #1 (x, v) = (1, 9) and Cat #2 (x, v) = (100, 10).
It is proposed that you get cats in order from closest to farthest. Counterexample: Cat #1 (x, v) = (1, 1) and Cat #2 (x, v) = (2, 100).
Detailed Derivation:
Let c(k) refer to the kth cat the lady picks up, v(k) refer to the speed of that cat and x(k) to the cat's initial displacement (at time t = 0, which we set a the time the lady starts her motorcycle initially in pursuit of the first cat).
The total time taken to get the first cat is:
t(1) = 2 * x(1) / (w - v(1))
where w is the constant speed of the motorcycle. Since this expression is going to be important we can motivate every part of it:
2 * comes from the fact that the lady must catch the cat, and then spend the same amount of time to return the cat home;
x(1) / (w - v(1)) is the time taken to reach the cat, that is, close the distance x(1) by traveling w - v(1) faster than the cat's v(1).
The time to get the first two cats is:
t(2) = t(1) + 2 * (x(2) + v(2)t(1)) / (w - v(2))
That is, it takes time equal to the time to get the first cat plus the time to get the second cat. The extra v(2)t(1) term accounts for the fact that the second cat moves while the lady is getting the first cat; otherwise, this part is the same.
Rearranging this expression, we get:
t(2) = t(1)(1 + 2 * v(2) / (w - v(2))) + 2 * x(2) / (w - v(2))
We define the following derivative terms:
T(k) = 2 * x(k) / (w - v(k))
s(k) = 2 * v(k) / (w - v(k)) + 1
Now we rewrite:
t(1) = T(1)
t(2) = s(2)T(1) + T(2)
and continue
t(1) = T(1)
t(2) = s(2)T(1) + T(2)
t(3) = s(3)s(2)t(1) + s(3)T(2) + T(3)
...
t(n) = s(n)...s(2)T(1) + s(n)...s(3)T(2) + ... + T(n)
This last expression gives us the total time to get all n cats:
s(n)...s(2)T(1) + s(n)...s(3)T(2) + ... + T(n)
Now we assume that we have an optimal solution in that the cats are picked up in the most efficient order possible. To derive useful properties about this hypothetical optimal solution, we can use the supposed optimality to infer that swapping cats produces a solution that is no better. Imagine swapping cats j and j+1:
... + s(n)...s(j+1)T(j) + s(n)...s(j+2)T(j+1) + ...
<= ... + s(n)...s(j)T(j+1) + s(n)...s(j+2)T(j) + ...
Terms involving T(k) for k < j have both s(j) and s(j+1) and by the commutativity of multiplication they are unaffected by the swap. Terms involving T(k) for k > j + 1 have neither s(j) nor s(j+1) and so cannot be affected by the swap. Only the terms with T(k) such that j <= k <= j + 1 are affected by the swap, so we can remove like terms:
s(n)...s(j+2)s(j+1)T(j) + s(n)...s(j+2)T(j+1)
<= s(n)...s(j+2)s(j)T(j+1) + s(n)...s(j+2)T(j)
The partial product s(n)...s(j+2) is common to all remaining terms and must be positive, so we can remove this like term by dividing both sides of the inequality:
s(j+1)T(j) + T(j+1) <= s(j)T(j+1) + T(j)
Rearrange this as follows:
(s(j+1) - 1)T(j) <= (s(j) - 1)T(j+1)
Finally:
(s(j+1) - 1) / T(j+1) <= (s(j) - 1) / T(j)
Recalling our definitions of s(k) and T(k), simplify to put this in terms of v and x:
v(j+1) / x(j+1) <= v(j) / x(j)
That is: if we have an optimal solution, it must be the case that the ratio of cats' speeds to initial displacements must be in descending order. This is a necessary, but perhaps not sufficient, condition.
Note that this result agrees with intuition:
Get still cats last (v = 0)
Get cats that haven't left yet first (x = 0)
Get cats approaching the motorcycle's speed first (or never)
Get cats that are really far away last (x -> +inf)
It also gives the correct result for the two-cat case; and in that case, if the ratios of speed to displacement are equal, then it can be easily shown that it doesn't matter which order you get the cats in (if they are unequal, you must get the cat with the higher ratio first).
Now - I have not addressed the case where cats may have the same ratio. It's not immediately obvious to me that the order in which you get cats with the same ratio doesn't matter.
However, suppose you have chosen optimally up until some point k < n. Now you need to decide which of two cats with the same ratio to go after. As we already mentioned, for the two-cat problem, it's a wash: so I think the answer is that it can't matter which one you choose, as either order among the two will take the same time and "look" the same afterwards. To see that two cats that start with the same ratio keep the same ratio:
v(i) / x(i) = c; X(i) = x(i) + v(i)t = x(i) + x(i)ct = x(i)(1 + ct)
v(j) / x(j) = c; X(j) = x(j) + v(j)t = x(j) + x(j)ct = x(j)(1 + ct)
So the ratio changes over time (if you take X as the new initial displacement) but two cats that start out with the same ratio will keep it. The new ratio will be:
v / x = c; v / X = v / x(1 + ct) = c / (1 + ct)
It is important to note that these ratios don't "cross over" each other either; if you start out with a higher or lower ratio, it will change over time, but it will not become higher or lower than other cats' ratios:
c(i) / (1 + c(i)t) > c(j) / (1 + c(j)t)
<=> c(i) + c(i)c(j)t > c(j) + c(i)c(j)t
<=> c(i) > c(j)
Based on all of these considerations, my best answer is:
Sort the cats according to the metric v / x in descending order. It doesn't matter how you break ties. Get the cats in that order.
Update
Thanks to #Patrick87 counterexample, I know my solution does not work in the general case, however, I'm going to leave it here because it provides a simpler solution under the extra assumption that all cats start their moves from the home at time 0. Please see #Patrick87 solution for a general solution.
Short Answer:
She must start with the fastest cat. i.e, order cats by velocity (in decreasing order).
Simplify the problem: Assume there are only two cats, one is running the other one walking very slowly. Which one you will go after first?
Detailed answer:
The total distance of all cats from home at time 0 is 0:
X(0) = 0
Therefore, if we assume that the woman catches the last cat at time Tn then the total distance the woman has traveled at Tn is:
X(Tn) = (V1 * T1) + ... + (Vn * Tn)
Where Ti is the time she catches the n's cat. Vi values are predetermined, so, we need to minimize this equation based on values of Ti.
We have n POSITIVE V values with n positive T coefficients to assign to them. Minimizing it under these conditions is easy:
Give the largest V, the smallest coefficient T and so on.
Which means start with the fastest cat (largest V) and bring it back first (multiply by smallest T) and continue.

Algorithm that uses second powers of linear series

I'm not quite sure if it should come here or on mathematics stack exchange, posting here to find more practical cases.
Is there any formula / algorithm that uses second powers of linear series?
Meaning: a(1)^2 + a(2)^2 + a(3)^2 + ... + a(n)^2
Where a(n) is linear series.
Let a_k = a_0 + d°(k-1)
Then: (I use ° for multiplication)
sum(a_k^2) = sum( (a_0 + d°(k-1))^2) =sum( a_0^2 + d°d°(k-1)^2 + 2°d°(k-1)) = n°a_0°a_0 + d°d°sum((k-1)^2) + 2°d°sum(k-1)
(The sum goes from 1 to n)
We know that sum(k) = n°(n+1)/2, and sum(k^2)=n°(n+1)°(2n+1)/6
Therefore the above
sum(a_k^2) = n°a_0°a_0 + d°d°(n-1)°n°(2n-1)/6 + 2°(n-1)°n/2
Which can be simplified a little more, and be calculated in constant time.

Algorithm task based on a variation of Fibonacci sequence [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Being given parameters C and M, help decrypt a list of encrypted
integers. The former parameter is used for generating {a_n} and {s_n}
sequences, defined as follows:
a_1 = a_2 = 1
forall n>=1: a_(n+2) = C * a_(n+1) + a_n
forall n: s_n = a_1 + a_2 + a_3 + ... + a_n
The ciphertext consists of T natural numbers. Each of them encrypts
one result number. In order to restore the original x value, it is
necessary to determine the result of the following operation: s_x mod
M
Input: two natural numbers C and M, T denoting number of tests and T
lines consisting of only one x number.
1 <= C, M <= 10^18 1 <= T <= 1000 1 <= x <= 10^18
Example input:
1 10 5 2 3 4 10 1
Example output:
2 4 7 3 1
It's a problem that showed up at the Deadline24 algorithmic competition which took placce this morning and for the love of all that's holy, I couldn't think of any way of pruning the calculations so that you don't have to do 10^18 operations in the worst case scenario.
Any brute force approach is immediately cut out because of that, so is a naive recursion approach. We may note that the sequence is a variation on the Fibonacci sequnece but it doesn't help much as the sequences with C != 1 are divergent from the regular Fibonacci sequence and thus we can't apply any of the approximations like Binet's Fibonacci number formula to calculate F_(n+2) - 1 which would normally be the sum of the first n Fibonacci numbers.
I thought of expressing the terms with C only and applying some fast modpow but it falls short both because it's slow (we still have to calculate the coefficient at each term which is a loop for every power in the final sum) and hard to compute (it looks like there is a pattern but it soon becomes tedious and hard to prove how it will progress).
What's a good way of solving this for max inputs?
We can use matrix exponentiation to get a logarithmic solution:
f(n) = C*f(n - 1) + f(n - 2)
a b f(n)
* = [f(n + 1) f(n)]
c d f(n - 1)
This results in:
a = C
b = 1
c = 1
d = 0
So you can use this matrix to get the n-th term of your function. As for the sum, notice that:
f(n) = Cf(n - 1) + f(n - 2)
f(n - 1) = Cf(n - 2) + f(n - 3)
...
f(3) = Cf(2) + f(1)
=============================== +
s(n) - 2 = C(s(n - 1) - 1) + s(n - 2)
s(n) = Cs(n - 1) + s(n - 2) - (C - 2)
This isn't as nice as what you can do for the Fibonacci numbers (expressing the sum in terms of a single Fibonacci number), but it can be solved by exponentiation by squaring using a similar (3 x 3) matrix to the one of the initial recurrence, which you can find using the same method, and with different starting conditions:
s(1) = 1
s(2) = 2
Let's go through and try to simplify the calculations at each step. First, we should look for a non-recursive formula for a_n. There is a closed form solution for this Recurrence Relationship that gives us a_n = A * r_1**n + B * r_2**n where r_1 and r_2 are the solutions to the equation r**2 = C * r + 1, based on the recurrence relation in the problem. Then we can solve for A and B so that a_1 = a_2 = 1.
Now, we can consider s_n which based on our formula for a_n, and rearranging terms, becomes:
s_n = A * (r_1 + r_1**2 + ... + r_1**n) + B * (r_2 + r_2**2 + ... + r_2**n)
Now, using the formula for the Sum of a Geometric Progression, we get the formula
s_n = A * r_1 * (1 - r_1**n) / (1 - r_1) + B * r_2 * (1 - r_2**n) / (1 - r_2)
This gives you a basic outline for how to proceed. There are a number of things to consider when actually implementing:
The formula for a_n changes if r_1 = r_2. That won't happen in this problem. Why?
If r_1 = 1 or r_2 = 1, the formula calls for dividing by 0.
Integer overflow.
The modular arithmetic at the end.

Interview question - Finding numbers

I just got this question on a SE position interview, and I'm not quite sure how to answer it, other than brute force:
Given a natural number N, find two numbers, A and P, such that:
N = A + (A+1) + (A+2) + ... + (A+P-1)
P should be the maximum possible.
Ex: For N=14, A = 2 and P = 4
N = 2 + (2+1) + (2+2) + (4+2-1)
N = 2 + 3 + 4 + 5
Any ideas?
If N is even/odd, we need an even/odd number of odd numbers in the sum. This already halfes the number of possible solutions. E.g. for N=14, there is no point in checking any combinations where P is odd.
Rewriting the formula given, we get:
N = A + (A+1) + (A+2) + ... + (A+P-1)
= P*A + 1 + 2 + ... + (P-1)
= P*A + (P-1)P/2 *
= P*(A + (P-1)/2)
= P/2*(2*A + P-1)
The last line means that N must be divisible by P/2, this also rules out a number of possibilities. E.g. 14 only has these divisors: 1, 2, 7, 14. So possible values for P would be 2, 4, 14 and 28. 14 and 28 are ruled our for obvious reasons (in fact, any P above N/2 can be ignored).
This should be a lot faster than the brute-force approach.
(* The sum of the first n natural numbers is n(n+1)/2)
With interview questions, it is often wise to think about what is probably the purpose of the question. If I would be asking you this question, it is not because I think you know the solution, but I want to see you finding the solution. Reformulating the problem, making implications, devising what is known, ... this is what I would like to see.
If you just sit and tell me "I do not know how to solve it", you immediately fail the interview.
If you say: I know how to solve it by brute force, and I am aware it will be probably slow, I will give you some hints or help you to get you started. If that does not help, you most likely fail (unless you show some extraordinary skills to compensate for the fact you are probably lacking something in the field of general problem analysis, e.g. you will show how to implement a solution paralelized for many cores or implemented on GPU).
If you bring me a ready solution, but you are unable to derive it, I will give you another similar problem, because I am not interested about solution, I am interested in your thinking.
A + (A+1) + (A+2) + ... + (A+P-1) simplifies to P*A + (P*(P-1)/2) resp P*(A+(P-1)/2).
Thus, you could just enumerate all divisors of N, and then test each divisor P to the following:
Is A = (N-(P*(P-1)/2))/P (solved the first simplification for A) an integral number? (I assume it should be an integral number, otherwise it would be trivial.) If so, return it as a solution.
Can be solved using 0-1 Knapsack solution .
Observation : N/2 + N/2 + 1 > N
so our series is 1,2,...,N/2
Consider the constraints of W=N and vi =1 for all elements, I think this trivially maps to 0-1 knapsack, O(n^2)
Here is a O(n) solution.
It uses the property of the sum of an arithmetic progression.
S = difference*(first_term + last_term)/2
Here our sum is N, the difference is P and first term is A.
Manipulation the above equation we get some equations and we can iterate P from 1 to n - 1 to get a valid A.
def solve(n,p):
return (2*n - (p**2) + p)/(2*p)
def condition(n,p,a):
if (2*n == (2*a*p) + (p**2) - p) and (a*-1 < 0):
return True
else:
return False
def find(n):
for x in xrange(n,-1,-1):
a = solve(n,x)
if condition(n,x,a):
return n,x,a

Resources