Author |
Topic: Decimal repeat (Read 867 times) |
|
mad
Junior Member
Posts: 118
|
|
Decimal repeat
« on: Aug 2nd, 2007, 6:46am » |
Quote Modify
|
Given Numerator & Denominator.Print 1/3 o30.3333333333 as .(3) and 0.123123 as .(123)
|
|
IP Logged |
|
|
|
baba
Newbie
Gender:
Posts: 14
|
|
Re: Decimal repeat
« Reply #1 on: Aug 21st, 2007, 3:27am » |
Quote Modify
|
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...
|
|
IP Logged |
|
|
|
baba
Newbie
Gender:
Posts: 14
|
|
Re: Decimal repeat
« Reply #2 on: Aug 21st, 2007, 3:36am » |
Quote Modify
|
something similar to... hidden: | #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(")"); } } } | 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....
|
« Last Edit: Aug 21st, 2007, 3:39am by baba » |
IP Logged |
|
|
|
|