You are not logged in. Please login at www.codechef.com to post your questions!

×

Resistance- How do i fix this code ?

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 ?

asked 04 Mar '14, 11:55

nuke's gravatar image

2★nuke
112
accept rate: 0%

edited 05 Mar '14, 13:56


-2

can you explain your logic clearly?

link

answered 04 Mar '14, 12:57

prakashjaggi's gravatar image

0★prakashjaggi
393
accept rate: 0%

toggle preview
Preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:

×1,664
×1,490
×545
×4

question asked: 04 Mar '14, 11:55

question was seen: 874 times

last updated: 05 Mar '14, 13:56