I was solving this problem on SPOJ
We are to calculate ( (P^N) + (Q^N) ), we are given
P+Q and P*Q.
Input :
first line will contain an integer T (<=15) denoting the number of test cases
three integers p+q, p*q and n will be given for each test case in a separate line
for every test case output the corresponding
output (p^n)+(q^n) in a separate line
After some time I came up with this recurrence
p^n + q^n = (p^n-1 + q^n-1)(p+q) - pq(p^n-2 + q^n-2)
and in my code i have
a = p + q and b = p.q
Here is my solution
public Long computeExponential(int n)
{
//base cases
if(n == 0)
{
return 1L;
}
else if(n == 1)
{
return new Long(a);
}
else
{
return (a * computeExponential(n-1) - b * computeExponential(n-2));
}
The answers that I get with the given testcases is
2125764
4383653
-3
175099
28160
Is the formula that I have derived wrong?
No, your derived equation is spot-on. Just a wee error in your implementation that I can see:
If
n=0,p^0 + q^0 = 1 + 1 = 2. YourcomputeExponentialforn=0returns1.[edit]For future reference, I find it quite helpful, for complicated algorithms especially, to write my own test cases, especially for the base cases, simple cases, and outliers, that I have manually calculated the results for and then run these first to check my function is doing what I think it should. Testing your method with n=0, p=2, q=3 (i.e. p+q=5, pq=6) for example would have thrown this error up pretty quickly. Only once it passes my own test cases would I then submit it to other test data which may, or may not, have any meaning to me.