This question doesn't need to apply to just terminating decimals - repeating decimals can also be converted to fractions via an algorithm.

Your task is to make a program that takes a repeated decimal as input, and output the corresponding numerator and denominator (in lowest terms) that produces that decimal expansion. Fractions greater than 1 should be represented as improper fractions like 9/5. You can assume that input will be positive.

The repeated decimal will be given in this format:


with everything after the second dot repeated, like this:


Your program will output two integers representing the numerator and denominator, separated by a slash (or the equivalent form in your language if you do not output plain text):


Note that terminating decimals will have nothing after the second dot, and decimals with no non-repeating decimal portion will have nothing between the two dots.

Test cases

These test cases cover all of the required corner cases:

0..3 = 1/3
0.0.3 = 1/30
0.00.3 = 1/300
0.6875. = 11/16
1.8. = 9/5
2.. = 2/1
5..09 = 56/11
0.1.6 = 1/6
2..142857 = 15/7
0.01041.6 = 1/96
0.2.283950617 = 37/162
0.000000.1 = 1/9000000
0..9 = 1/1
0.0.9 = 1/10
0.24.9 = 1/4

If you wish, you can also assume that fractions without integer parts have nothing to the left of the first dot. You can test that with these optional test cases:

.25. = 1/4
.1.6 = 1/6
..09 = 1/11
.. = 0/1
  • 1
    \$\begingroup\$ Is it necessary to simplify the fraction? Or is it reasonable to leave it in an unsimplified form (eg: 9/99)? \$\endgroup\$
    – Justin
    Commented Jan 7, 2014 at 18:57
  • 4
    \$\begingroup\$ (in lowest terms) i.e. the fraction must be simplified. \$\endgroup\$
    – Joe Z.
    Commented Jan 7, 2014 at 18:58
  • 3
    \$\begingroup\$ Am I allowed to output 13 instead of 13/1? \$\endgroup\$
    – mniip
    Commented Mar 14, 2014 at 13:56
  • 4
    \$\begingroup\$ Be sure to handle this input 1.9999... and output 2/1 \$\endgroup\$ Commented Mar 14, 2014 at 20:08
  • 3
    \$\begingroup\$ @ThomasEding 1.9999. is 19999/10000, to get 2/1 you need 1..9, isn't it? \$\endgroup\$
    – Qwertiy
    Commented Dec 5, 2014 at 8:07

21 Answers 21


Perl 6 (93 101 100 80 68 66 bytes)

$/=split ".",get;say ($0+($1+$2/(9 x$2.comb||1))/10**$1.comb).nude

The size was increased to handle nothing, instead of just failing. Mouq proposed to use $/, so it's now being used, and the code is 20 bytes shorter. Ayiko proposed replacing / with , so the code is even shorter (by 12 bytes). Then Mouq proposed replacing chars with comb (in numeric context, they are identical, because list of characters after conversion to number is number of characters).

Sample output:

$ perl6 script.p6
889 165
$ perl6 script.p6
2 1
$ perl6 script.p6
1 3
$ perl6 script.p6
1 30
$ perl6 script.p6
0 1
$ perl6 script.p6
1 6
$ perl6 script.p6
1 96
$ perl6 script.p6
37 162
$ perl6 script.p6
41111111 333000
  • \$\begingroup\$ Unfortunately, it turns out that using zero as a placeholder between two dots is a no-go. 0..09 returns 1/11, but 0.0.09 returns 1/110. \$\endgroup\$
    – Joe Z.
    Commented Jan 7, 2014 at 19:32
  • \$\begingroup\$ @JoeZ. Oh, ok. I updated my code to handle the case when nothing is typed. \$\endgroup\$
    – null
    Commented Jan 7, 2014 at 19:37
  • \$\begingroup\$ I don't know Perl 6, but am I correct in guessing that given 'a.b.c', your program uses exact rational arithmetic to compute c/99...9, but only uses floating point to compute a.b? In that case if b has many digits it will give an incorrect answer. \$\endgroup\$
    – Omar
    Commented Mar 14, 2014 at 14:16
  • \$\begingroup\$ @OmarAntolín-Camarena: Not quite. In Perl 6, rationals are default, not floating point numbers. For example, 0.1 + 0.2 == 0.3 in Perl 6. \$\endgroup\$
    – null
    Commented Mar 14, 2014 at 14:32
  • 2
    \$\begingroup\$ Golfed to 80 chars: $/=split ".",get;say join "/",($0+($1+$2/(9 x chars $2 or 1))/10**$1.chars).nude :) \$\endgroup\$
    – Mouq
    Commented Mar 15, 2014 at 17:57

Dyalog APL (75 73 69 68 characters)

Here is another and fifth attempt (most probably my last one); I spent the day trying to write some piece of code shorter than 80 characters and being fully consistent with the rules. This challenge made my day!

I finally got a line of APL made of 75 characters, working with Dyalog APL (but not on the online interpreter page because using the execute function), which is the following one:

(N,D)÷D∨N←(⍎'0',1↓I/⍨2=+\P)+(⍎'0',I/⍨2>+\P)×D←D+0=D←⍎'0',⌽2↓⍕¯1+10⊥P←'.'=I← '1.2.3'

Of course I could make it a little shorter, but the special cases where one, two or three fields are missing. My code can even handle the .. input case.

I know that APL is difficult to read, and since people enjoy understanding how a piece of code actually works, here are some explanation. Basically, I compute the final denominator in the variable D and the final numerator in the variable N.

APL is parsed from right to left.

  • First, the string is stored in variable I (I←).
  • Then it is mapped to a vector of booleans indicating where a dot is, and this vector is called P (P←'.'=). For instance '1.2.3' will be mapped to 0 1 0 1 0.
  • This vector is digits in base 10 (10⊥); now '1.2.3' is 1010.
  • Then 1 is substracted from this number (either with 1-⍨ or with ¯1+, here I chose the second). Now '1.2.3' is 1009.
  • Then this number is converted to a string (), two initial digits are removed (2↓), which makes 09 from our initial '1.2.3' example; the string is reversed ().
  • Here, as a special case, I add an initial 0 character in front of the string; it makes me sad to use the four characters '0', but I did it for avoiding an error when the second and thirds fields are both empty. The string is converted back to a number () and it is stored in D, which is the denominator except when both last fields are empty, because in such case D is equal to 0.
  • The D←D+0= piece of code set D to 1 if it is currently null, and now D contains the denominator (before GCD division however).
  • This denominator is multiplied (×) with the content of the initial string I up to the second dot with (⍎'0',I/⍨2>+\P) which starts from P again (0 1 0 1 0 in my example), adds the successive numbers by cumulating them (which makes 0 1 1 2 2 in my example), check which values are smaller than 2 (making the boolean vector 1 1 1 0 0), and taking corresponding characters in I; another 0 is added in front of the string for preventing another trap (if the two initial fields are empty) and the whole is converted to a number.
  • The last part of the input string is added to the previous product with (⍎'0',1↓I/⍨2=+\P), which takes P again, adds by cumulating again, check which values are equal to 2 (see previous explanation), takes the characers, removes the first one which is a dot, adds a preventing initial 0 character and converts to a number.
  • This product followed with a sum is stored in N which is the numerator.
  • Finally the GCD is computed with D∨N and both numbers are divided by this GCD.

edit: Here is a fix for 73 characters:


The idea of this hack is computing first the case where cumulative addition has values equal to 2, storing them for later and inverting this bitwise mask for getting the first case; thus computing the next case needs less characters.

edit: Here is another fix for 69 characters:


The idea of this hack is to embed the most complicated special case as APL code in the string to be evaluated (at string to number conversion stage).

edit: Here is another fix for 68 characters:


The idea of this hack is to replace adding -1 to the value for substracting 1 to that value by the operation substracting that value to 1 then remove later one character more at the beginning (which will be the minus sign).

edit: Cosmetic change:


No improvement in size, but more satisfied to get the maximum function out of the code to be evaluated.

  • \$\begingroup\$ I attempted to run this with tryapl.org and it complains INVALID TOKEN. Do you know why? \$\endgroup\$ Commented Mar 22, 2014 at 19:19
  • \$\begingroup\$ @Peter Taylor: Yes, it is even said in my message; this is because I use the "execute" operator which would be unsafe for the server of Dyalog and has been disabled online (safe mode). You have to try it on an installed version of Dyalog APL. \$\endgroup\$ Commented Mar 22, 2014 at 19:28
  • \$\begingroup\$ Ah, shame. I'm not going to spend 60€ to be able to test an occasional PCG submission. I've found an alternative online APL tester, but there seems to be something Dyalog-specific in your code because it gives rank errors or length errors. \$\endgroup\$ Commented Mar 22, 2014 at 19:41
  • \$\begingroup\$ @Peter Taylor; no ;-) Please, use my own website (still experimental and not official) with GNU APL; but I had to add two characters to make it compatible (parenthesis around one I): see this permalink \$\endgroup\$ Commented Mar 22, 2014 at 19:54
  • \$\begingroup\$ We've expanded the capabilities of the online "safe mode", but Dyalog APL is also free for personal use now. \$\endgroup\$
    – Adám
    Commented Dec 13, 2021 at 14:24

J (85 90 89 chars)

My original function, which was 5 characters shorter than the second, had a couple of bugs: it didn't output integers as "n/1" and it gave the wrong answer on numbers with more than a dozen or so digits. Here's a corrected function in J that also incorporates Eelvex's suggestion to save a character:

f=:3 :0
'a t'=.|:(".@('0','x',~]),10x^#);._1'.',y
(,'/'&,)&":/(,%+.)&1+/a%*/\1,0 1-~}.t

It receives a string and returns a string. Here's a sample session:

   f '..'
   f '0.0.0'
   f '3..'
   f '..052631578947368421'
   f '0.2.283950617'
   f '.0.103092783505154639175257731958762886597938144329896907216494845360824742268041237113402061855670'
  • \$\begingroup\$ You should fix your function to output 0/1 and 3/1 inf first two test cases, See this comment \$\endgroup\$
    – mniip
    Commented Mar 14, 2014 at 20:15
  • \$\begingroup\$ I fixed the output for integers at the cost of 5 chars, @mniip. \$\endgroup\$
    – Omar
    Commented Mar 14, 2014 at 23:54
  • \$\begingroup\$ Use ('0','x',~]) and save a byte. \$\endgroup\$
    – Eelvex
    Commented Mar 16, 2014 at 1:32

C, 171

Quite long. Could be further reduced. No scanf, which really can't handle it if there aren't any numbers between the dots. No strtol. Just number crunching:



rfc <<< "2..142857"

DC (not fully general, shortened to 76 characters)

Not fully general, but please, consider I did it with one of the oldest things in the world:

5.3.87 dsaX10r^d1-rla*sasbdscX10r^dlc*rlb*rlb*la+snsdlnld[dSarLa%d0<a]dsax+dldr/rlnr/f

Edit: I edit my solution; it isn't more general, but a little shorter:


Use it as:

5.3.87 sadsbX10r^sclaX10r^dd1-dsdlblc**rla*+dsnrld*dsd[dSarLa%d0<a]dsax+dldr/rlnr/f
  • First field isn't required:

    .1.3 sadsbX10r^sclaX10r^dd1-dsdlblc**rla*+dsnrld*dsd[dSarLa%d0<a]dsax+dldr/rlnr/f

    is OK.

  • Second and thirst field require at least one digit


Javascript, 203

Way too long, but still fun. Newlines because semicolons are unreadable.

function g(a,b){return b?g(b,a%b):a}g=g(a,b);a/g+"/"+b/g
  • \$\begingroup\$ I'm getting 889/NaN when I run 5.3.87 ... Am I doing something wrong? \$\endgroup\$
    – user15260
    Commented Mar 17, 2014 at 14:29
  • \$\begingroup\$ I don't know... If I just paste this code in the Safari console (Firefox or Chrome should do too), hit enter and type "5.3.87", I just get "889/165" in the console. How are you running it? @rafaelcastrocouto \$\endgroup\$
    – tomsmeding
    Commented Mar 17, 2014 at 16:43
  • \$\begingroup\$ nevermind ... I guess I did something wrong since it is working now ... \$\endgroup\$
    – user15260
    Commented Mar 18, 2014 at 11:49
  • 1
    \$\begingroup\$ You can save 1 character by moving the b=1 part inside prompt(). \$\endgroup\$ Commented Apr 24, 2014 at 8:41
  • 1
    \$\begingroup\$ f=(P(10,s[2].length)-1)*P(10,l),f=f?f:1 => f=(P(10,s[2].length)-1)*P(10,l)||1 \$\endgroup\$
    – f.ardelian
    Commented Apr 14, 2015 at 15:55

J (different method)

Another solution based on a very different method; this time it is fully general; only missing is the 1-denominator when an integer is submitted:

   ".((({.~(i.&1)),'+'"_,((":@(10&^)@#,'%~',])@}.@#~~:/\),'+%',((,~(##'9'"_),'%x:0'"_)@}.@#~2:=+/\@]))(=&'.')) '.1.3'
   ".((({.~(i.&1)),'+'"_,((":@(10&^)@#,'%~',])@}.@#~~:/\),'+%',((,~(##'9'"_),'%x:0'"_)@}.@#~2:=+/\@]))(=&'.')) '.1.'
   ".((({.~(i.&1)),'+'"_,((":@(10&^)@#,'%~',])@}.@#~~:/\),'+%',((,~(##'9'"_),'%x:0'"_)@}.@#~2:=+/\@]))(=&'.')) '1..'
   ".((({.~(i.&1)),'+'"_,((":@(10&^)@#,'%~',])@}.@#~~:/\),'+%',((,~(##'9'"_),'%x:0'"_)@}.@#~2:=+/\@]))(=&'.')) '1..3'

GolfScript (67 chars)


NB This supports empty integer parts.

If the string is of the form 'n.p.q' then the value is n + p/E + q/(DE) = ((nD + p)E + q)/DE where D = 10^(len p) and E = 10^(len q) - 1, except when len q = 0, in which case E = 1 (to avoid division by 0).


           # Stack: 'n.p.q'
`{         # Combined with the }+ below this pulls the value into the block
           # Stack: idx 'n.p.q'
    '.'/   # Stack: idx ['n' 'p' 'q']
    1$=    # Stack: idx str   (where str is the indexed element of ['n' 'p' 'q'])
    .10\,? # Stack: idx str 10^(len str)
    @-)    # Stack: str 10^(len str)-idx+1
           #   If idx = 0 we don't care about the top value on the stack
           #   If idx = 1 we compute D = 10^(len 'p')
           #   If idx = 2 we compute E' = 10^(len 'q') - 1
    .!+    # Handle the special case E'=0; note that D is never 0
    0@+~   # Stack: 10^(len str)-idx+1 eval('0'+str) (GolfScript doesn't treat 011 as octal)
}+         # See above
3,/        # Run the block for idx = 0, 1, 2
           # Stack: _ n D p E q
1$4$*      # Stack: _ n D p E q D*E
]-1%~;     # Stack: D*E q E p D n
*+*+       # Stack: D*E q+E*(p+D*n)
].~        # Stack: [denom' num'] denom' num'
{.@\%.}do; # Stack: [denom' num'] gcd
{/}+/      # Stack: denom num
'/'@       # Stack: num '/' denom

Online demo which simulates running the program with each of the test inputs, one at a time.

  • \$\begingroup\$ I tried it, and it doesn't seem to follow all the rules: "Note that terminating decimals will have nothing after the second dot, and decimals with no non-repeating decimal portion will have nothing between the two dots." I couldn't make your code work with input being 0.1. \$\endgroup\$ Commented Mar 21, 2014 at 14:50
  • \$\begingroup\$ -1. I retried it another time after having noticed you got the +300 points. It isn't fair, because other solutions have done their best to follow all the rules, which you obviously haven't done. \$\endgroup\$ Commented Mar 22, 2014 at 15:50
  • \$\begingroup\$ @ברוכאל, I object to your assertion that I haven't tried to follow the rules. The position of the optional test cases confused me into thinking that the final block covered all of the required cases; it turns out that I was wrong, and I'm going to edit the question shortly to avoid other people making the same mistake. I have now updated my code to handle the previously unhandled corner cases, and updated my link to a test to demonstrate that. \$\endgroup\$ Commented Mar 22, 2014 at 19:15
  • \$\begingroup\$ that's OK. You probably deserve the 300 points. Being new to CodeGolf, these 300 points were a challenging target for me, and I am still disappointed not to have got them while I am still thinking that at the deadline time my code was the shortest to perfectly fit the rules. Anyway, I have all my life for winning points. Regards. \$\endgroup\$ Commented Mar 22, 2014 at 19:32
  • \$\begingroup\$ @ברוכאל: I wanted to start 500 points (yes, I'm generous like that, it's not that I can give less) bounty, and give you those points, but I guess there is already a bounty started. Well, whatever. I'm wondering when this bounty will end, and who will get those points. \$\endgroup\$
    – null
    Commented Mar 22, 2014 at 22:13


No libraries - 156 characters

_=lambda a,b:b and _(b,a%b)or a;a,b,c=raw_input().split('.');d,e=int(a+b+c)-bool(c)*int(a+b),

Using fractions - 127 characters

from fractions import*;a,b,c=raw_input().split('.');print Fraction(int(a+b+c)-bool(c)*int(a+b
  • \$\begingroup\$ The fractions version prints things like "Fraction(7, 5)" instead of "7/5", doesn't it? \$\endgroup\$
    – Omar
    Commented Mar 14, 2014 at 23:48
  • \$\begingroup\$ It doesn't; I'm not getting the top one working, by the way. _=lambda a,b:b and _(b,a%b)or a;a,b,c=raw_input().split('.');d,e=int(a+b+c)-bool(c)*int(a+b), ValueError: need more than 1 value to unpack \$\endgroup\$
    – tomsmeding
    Commented Mar 15, 2014 at 7:51
  • \$\begingroup\$ @OmarAntolín-Camarena AFAIK, print uses str when available, not repr. This is the output on my end: puu.sh/7w64w.png \$\endgroup\$
    – Oberon
    Commented Mar 15, 2014 at 11:50
  • \$\begingroup\$ @tomsmeding Both are on one line; the line break was added to make them fit in the answer. _=lambda a,b:b and _(b,a%b)or a;a,b,c=raw_input().split('.');d,e=int(a+b+c)-bool(c)*int(a+b),(10**len(c)-bool(c))*10**len(b);f=_(d,e);print'%i/%i'%(d/f,e/f) should go all in one line. \$\endgroup\$
    – Oberon
    Commented Mar 15, 2014 at 11:53
  • \$\begingroup\$ Oh right, @Oberon, as you can probably guess I wasn't at my computer and couldn't run the code. \$\endgroup\$
    – Omar
    Commented Mar 15, 2014 at 12:18

Mathematica, 143

As usual, Mathematica offers many high-level functions to do the job, but gives them verbose names.


Sample output to be added later when I have time.

  • \$\begingroup\$ It looks to me as if this outputs integers as n, rather than n/1. Is that right? (My solution has the same bug... :() \$\endgroup\$
    – Omar
    Commented Mar 14, 2014 at 20:02
  • \$\begingroup\$ Ah, now I see....specified in the comments. What an odd requirement...if every other fraction is reduced, why not allow n/1 to reduce to n? I'll add the extra ~50 bytes to convert integers later. \$\endgroup\$ Commented Mar 14, 2014 at 20:07
  • \$\begingroup\$ Your approach is fine. Mine makes use of FromDigits so I decided to post it too. \$\endgroup\$
    – DavidC
    Commented Mar 14, 2014 at 21:40

Ruby - 112


This is my first experiment with ruby, so feel free to suggest improvements.

$ ruby20 % <<< '5.3.87'
$ ruby20 % <<< '0..3'
$ ruby20 % <<< '0.0.3'
$ ruby20 % <<< '0.00.3'
$ ruby20 % <<< '0.6875.0'
$ ruby20 % <<< '1.8.0'
$ ruby20 % <<< '2..'
$ ruby20 % <<< '..'
  • \$\begingroup\$ Removing support "..' and ".1.2" means you're not following the spec, right? (I would prefer removing them too.) \$\endgroup\$
    – Omar
    Commented Mar 14, 2014 at 20:11
  • \$\begingroup\$ @OmarAntolín-Camarena On that particular point, the spec says, If you wish. I do not wish, so I'm not supporting fractions without 1st or 3rd group of digits. I am however supporting fractions lacking 2nd group of digits, which matches the spec. \$\endgroup\$
    – mniip
    Commented Mar 14, 2014 at 20:14
  • \$\begingroup\$ @minip, you misread the spec: it doesn't say "if you wish you can support .. and .1.2", it says, "if you wish, you can assume that 0.. and 0.1.2 are always given as .. and .1.2". \$\endgroup\$
    – Omar
    Commented Mar 14, 2014 at 20:47
  • \$\begingroup\$ @OmarAntolín-Camarena Point taken. Edited. \$\endgroup\$
    – mniip
    Commented Mar 14, 2014 at 20:53

C, 164

This is similar to orion's C solution, even though I did it from scratch. I confess however stealing a number of his optimizations. It is not much shorter, but it handles .25. = 1/4 and 0.000000.1 = 1/9000000.

long a,b,c,d,e;main(){while((c=getchar()-48)>-3)c+2?a=a*10+c,b*=10:b?e=a,d=b:(b=1);

Two python answers using no libraries. First handles the optional input without a digit before the first . and is 162 chars

_=lambda a,b:b and _(b,a%b)or a;i,t,r=raw_input().split(".");b=r!="";d=(10**len(r)-b)*10**len(t);n=int((i+t+r)or 0)-b*int((i+t)or 0);f=_(d,n);print "%i/%i"%(n,d)

Second doesn't handle nothing before the first digit but does handle all required inputs correctly and is 150 chars

_=lambda a,b:b and _(b,a%b)or a;i,t,r=raw_input().split(".");b=r!="";d=(10**len(r)-b)*10**len(t);n=int(i+t+r)-b*int(i+t);f=_(d,n);print "%i/%i"%(n,d)


import Data.Ratio
f n=case s '.' n of
    [x,y,z]->(r x)%1+(r y)%(10^(length y))+(r z)%((10^t-1)*(10^(length y)))
            r ""=0
            r n=read n
            t = if length z==0 then 9 else length z
s _ []=[[]]
s n (x:xs) | x==n = []:(s n xs)
           | otherwise = let (l:ls)=s n xs in (x:l):ls
  • \$\begingroup\$ Hey, this is code-golf, you aren't even trying! \$\endgroup\$
    – mniip
    Commented Mar 16, 2014 at 14:34
  • \$\begingroup\$ @mniip I am not good at code golf. Atleast I used single character variable names. \$\endgroup\$ Commented Mar 16, 2014 at 20:00
  • 1
    \$\begingroup\$ You never specified the language or the total amount of characters/bytes used. \$\endgroup\$
    – Justin Fay
    Commented Mar 19, 2014 at 23:31
  • 2
    \$\begingroup\$ Use {;} to save space on indents, span to implement s, add short aliases for functions, remove space where possible. import Data.Ratio v=span(/='.');w=tail;l=length;f n=(r x)%1+(r y)%p+(r z)%((10^t-1)*p)where{(x,b)=v n;(y,d)=v(w b);z=w d;p=10^(l y);r""=0;r n=read n;t=if null z then 9 else l z} - 178 chars, down from 321. NB True is a synonym for otherwise, null z is length z==0 \$\endgroup\$
    – bazzargh
    Commented Mar 20, 2014 at 12:30

JavaScript (ECMASCript 6) 180 175


While it isn't a clear winner for the 300 bounty... this is the shortest I can come up with:

  • Changes from previous version: some slight alteration to logic, and changes to the Power P function by altering it to +("1e"+a) instead of Math.pow(10,a) thereby saving a few more characters...

Mathematica 175

If[IntegerQ[g=FromDigits[Map[IntegerDigits@ToExpression@#&,StringSplit[i,"."]/.""-> {}]
/.{a_,b_,c_}:> {{Sequence@@Join[a,b],c},Length@a}]],HoldForm[Evaluate@g]/HoldForm@1,g]

Most of the routine goes to massaging the input. Approximately 50 chars went to handling integers.




More examples:

 Partition[{#, f[#]} & /@ {"19..87", "19.3.87", "5.3.87", "0.0.3", "0..3", "0.2.283950617", 
"123.456.789", "6666.7777.8888", "2.0.0","0.0.0"}, 5], TableSpacing -> {5, 5}]


How it would normally be accomplished in Mathematica

FromDigits can obtain a fraction directly from a recurring repeating decimal, provided that the input is of a particular form. Integers are displayed as integers.

z={{{1, 9, {8, 7}}, 2}, {{1, 9, 3, {8, 7}}, 2}, {{5, 3, {8, 7}}, 1}, {{{3}}, -1}, {{{3}}, 0}, 
{{2, {2, 8, 3, 9, 5, 0, 6, 1, 7}}, 0}, {{1, 2, 3, 4, 5, 6, {7, 8, 9}}, 3}, 
{{6, 6, 6, 6, 7, 7, 7, 7, {8}}, 4}, {{2}, 1}, {{0}, 1}}



  • \$\begingroup\$ Your output is in the wrong format, it is way too pretty. \$\endgroup\$
    – Omar
    Commented Mar 14, 2014 at 22:58
  • \$\begingroup\$ Strangely, this is the default format for expressing fractions in Mathematica. It would take several more characters to change this format to the simpler one. \$\endgroup\$
    – DavidC
    Commented Mar 15, 2014 at 13:28

J (96 characters)

I don't use the slash symbol as a separator (but solution in Mathematica doesn't either since it uses a graphical representation which is better anyway); in J language the fraction is displayed with r instead as /:

   (((-.@]#[)((".@[%#@[(10x&^)@-{.@])+({.@](10x&^)@-#@[)*<:@{:@](".%<:@(10x&^)@#)@}.[)I.@])(=&'.')) '1..3'
   (((-.@]#[)((".@[%#@[(10x&^)@-{.@])+({.@](10x&^)@-#@[)*<:@{:@](".%<:@(10x&^)@#)@}.[)I.@])(=&'.')) '123.456.789'

APL (not fully general)

Not fully general (like my solution for dc); works with Dyalog APL (but not on the online version of Dyalog APL, not sure why):

(R,F)÷(F←D×N)∨R←(⍎C)+D×(⍎I/⍨2>+\P)×N←10*¯1++/≠\P⊣D←¯1+10*⍴C←1↓I/⍨2=+\P←'.'=I← '123.456.789'

The first field is optional, but at least one digit is required for both other fields.


JavaScript (189)







C (420 characters as written; less after removing unnecessary whitespace)

Note that this assumes 64-bit long (e.g. 64 bit Linux); it will fail for the test case 0.2.283950617 on systems using 32-bit long. This can be fixed at the cost of some characters by changing the type to long long and changing the printf format string accordingly.

#include <stdio.h>

long d[3], n[3], i;

int main(int c, char** v)
  while (c = *v[1]++)
    case '.':
      n[++i] = 1;
      d[i] = 10 * d[i] + c - '0';
      n[i] *= 10;

  n[2] -= n[2] != 1;

  while (i--)
    d[2] += d[i] * n[i+1], n[i]*=n[i+1];

  i = d[2];
  *n = n[1];

  while (i)
    *d = i, i = *n%i, *n = *d;
  printf("%ld/%ld\n", d[2]/ *n, n[1]/ *n);
  • \$\begingroup\$ Nice. You can shave off 1 character by changing '0' to 48. \$\endgroup\$ Commented Apr 14, 2015 at 21:59
  • \$\begingroup\$ I think you could also save a few more by rewriting the switch statement as if(c==46) n[++i]=1; else d[i]=10*d[i]+c-48,n[i]*=10;. \$\endgroup\$ Commented Apr 14, 2015 at 22:10

GTB, 81



  • 4
    \$\begingroup\$ Until a compiler is made freely available for this language, I will downvote every answer which uses it. \$\endgroup\$
    – Gareth
    Commented Mar 14, 2014 at 18:33
  • 1
    \$\begingroup\$ There seems to be a compiler on the page linked above? \$\endgroup\$ Commented Mar 14, 2014 at 21:20
  • \$\begingroup\$ @skibrianski See this post on meta \$\endgroup\$
    – mniip
    Commented Mar 14, 2014 at 21:32
  • 2
    \$\begingroup\$ @Gareth, there are a couple of Mathematica answers for you to downvote, too. :P \$\endgroup\$
    – Omar
    Commented Mar 14, 2014 at 22:25
  • 2
    \$\begingroup\$ @OmarAntolín-Camarena There is a compiler/interpreter for Mathematica. GTB has none. Follow the GTB link above if you don't believe me. You'll get some compressed stuff for a proprietary program, then you'll search for that program and find that the site that claims to provide a download says it's not available. So how do we compile it? \$\endgroup\$
    – Gareth
    Commented Mar 14, 2014 at 22:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.