wu :: forums
(http://www.ocf.berkeley.edu/~wwu/cgi-bin/yabb/YaBB.cgi) |
riddles >> cs >> Decimal repeat
(Message started by: mad on Aug 2nd, 2007, 6:46am) |
|
Title: Decimal repeat
Post by mad on Aug 2nd, 2007, 6:46am
Given Numerator & Denominator.Print 1/3 o30.3333333333 as .(3) and 0.123123 as .(123)
|
Title: Re: Decimal repeat
Post by baba on Aug 21st, 2007, 3:27am
Since no one seems to bother about this one.....how abt keep dividing and remembering the quotient and remainder and when we get remainder same as any previously seen remainder...u got the recurring part...print the quotient as u want to... |
Title: Re: Decimal repeat
Post by baba on Aug 21st, 2007, 3:36am
something similar to...
[hideb]
#define MAXLEN 100
int FindInRemainder(int * remainder,int len) {
int i;
for(i=0;i<len;i++)
{
if(remainder[i]==remainder[len]) return(i);
}
return(-1);
}
void PrintRecurringFraction(int numerator,int denominator) {
if(denominator==0)
{
Console::WriteLine("Divide by zero");
}
char str[MAXLEN];
int remainder[MAXLEN];
int len=0,loc=0,i=0;
while(((loc=FindInRemainder(remainder,len-1))==-1) && len<MAXLEN)
{ numerator*=10;
str[len]=((numerator/denominator)%10)+'0';
numerator=remainder[len++]=numerator%denominator;
}
//Check that u find a recurring fraction and didn't run out of range
if(len<MAXLEN)
{ Console::Write("0.");
for(i=0;i<loc;i++) { Console::Write(str[i]-'0'); }
//Check to see if the repeating part doesn't consist only of 0's as in 1/5= 0.2(0)
if(remainder[loc]!=0)
{
Console::Write("(");
i=loc;
while(i<len-1)
{
Console::Write(str[i]-'0');
++i;
}
Console::Write(")");
}
}
}
[/hideb]
It assumes that input is a proper fraction and it can be easily be extended to other fractions.....also complexity can be improved by using better methods for storing and searching remainder sorry abt formating it really sucks.... |
Powered by YaBB 1 Gold - SP 1.4!
Forum software copyright © 2000-2004 Yet another Bulletin Board |