Quantcast
Channel: CodeChef Discuss - latest questions
Viewing all articles
Browse latest Browse all 40121

Resistance- How do i fix this code ?

$
0
0

This is the code 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) = 2A and denominator = 2B + 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 ?


Viewing all articles
Browse latest Browse all 40121

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>