 # Resistance- How do i fix this code ?

This is the

``````
 i have written for the [resistance] problem.

I have written recursive functions to calculate numerator and denominator. In the end I am reducing the fraction by recursively dividing numerator and denominator by their gcd until the gcd becomes 1.

As per the formula 1/R = 1/R1 + 1/R2 ,therefore at any given time 1/R(n) = 1/R(n-1) + 1/2

where R(n) is the equivalent resistance when there are n blocks.
![alt text]

Say  R(n-1) = A/B , thus 1/R(n) = B/A + 1/2
Thus numerator of R(n) = 2*A and denominator = 2*B + A

I have written two functions for calculating these.

//numerator calculator

long  int num_calc(long  int n)

{
if(n==1)
return 1;

else return 2*num_calc(n-1);
}

//denominator calculator

long  int den_calc(long  int n)

{
if(n==1)
return 1;

else return 2*den_calc(n-1) + num_calc(n-1);
}

After that I keep reducing the fraction by continuously, dividing numerator and denominator by their gcd, until the gcd is 1.

//calculates the reduced form of the fraction
//num is the numerator and den is the denominator in the code

void lowest_fraction(long  int a, long  int b)

{
if(gcd(a, b)==1)
{
num = a;
den = b;
}

else(lowest_fraction((a/gcd(a,b)), (b/gcd(a,b))));

}

It works for n<29 but I start getting errors when n >=29

Can anyone please suggest any fixes for the code ?

: http://www.codechef.com/viewsolution/3497356
: http://www.codechef.com/problems/RESIST#comment-74413
: http://discuss.codechef.com/upfiles/resistance_1.png``````

can you explain your logic clearly?