Sign up ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Implement a function divide(int a, int b, int c) that prints the base 10 value of a/b. without using any floating point math nor BigInteger/BigDecimal or equivalent libraries whatsoever. At least c accurate characters within the set of 0123456789. must be printed, except for the (possible) exception in point 4 below.

  1. a and b may be any 32 bit integers. Update: If, for golfing purposes, you would like to have input be 64 bit primitives that is okay, but you do not need to support the whole 64 bit range of data.
  2. You do not need to check that c is positive (though hopefully your program does not crash) if it's not.
  3. The minimum supported upper bound for c is 500. It is okay if your program does not support values of c above 500, but it is also okay if it does.
  4. For numbers that divide evenly, it is your choice whether to print extra zeroes (based on the value of c) or nothing.
  5. You do not need to be able to use the function to do any further tasks with the quotient, the only goal is printing.
  6. For numbers between -1 and 1, it is your choice whether to print a leading 0. However, this is the only scenario where printing a leading zero is acceptable, and you may only print one such zero.
  7. You may use any rounding / floor / ceil logic you prefer for the last decimal place.
  8. For a negative answer, you must print a leading -. This does not count towards c. However, it is your choice if you wish to print , +, or nothing for a positive answer.
  9. Integer division and integer modulus are both allowed. However, keep in mind that you are restricted to primitives, unless you choose to implement your own BigInteger/BigDecimal library which counts against your code length.
  10. You do not need to handle b being 0, though you can if you want. Your program may enter an infinite loop, or crash, if b=0, and you will not be penalized.
  11. Slight rule change per comment. To make sure the playing field is level, while a and b are guaranteed to be 32 bit integers, you may use 64 bit long integers. If your chosen language goes beyond 64 bit integers as a primitive, you may not at any point use that functionality (pretend it is capped at 64 bits).
  12. Another point that is unclear (it shouldn't change any of the current valid answers, though): while c may be interpreted as either the number of printed characters or the number of spaces after the decimal, your program must use c somehow in a relevant way to decide how many characters to print. In other words, divide(2,3,2) should be much shorter output than divide(2,3,500); it is not okay to print 500 characters without regard to c.
  13. I actually don't care about the name of the function. d is okay for golfing purposes.


Both a function call and reading from stdin are accepted. If you read from stdin, any character not in the set [-0123456789] is considered an argument delimiter.


Characters to stdout as described above.


for divide(2,3,5), all of the following are acceptable outputs:


Another example: for divide(371,3,5) the following are all acceptable outputs:


And for divide(371,-3,5) the following are are all acceptable:

share|improve this question
For the sake of a level playing field, it might be wise to give a specific maximum bit length that can be used (primitive or otherwise) unless you roll your own larger implementation, because a) in some languages bit length of primitives varies depending on the underlying architecture and b) in some languages big number types are primitives. – Jonathan Van Matre Feb 25 '14 at 22:34
@JonathanVanMatre Added rule 11 per your comment – durron597 Feb 25 '14 at 22:50
How do you count accurate digits? In your example I see three or four but never five as the last argument indicates. – Howard Feb 26 '14 at 6:07
@Howard, if you did 92,3,5 the answer would be, for example, 30.67 – durron597 Feb 26 '14 at 10:32
btw 370/3=123.333 lol – izabera Feb 26 '14 at 11:34

9 Answers 9

up vote 3 down vote accepted

Java, 92/128

void d(long a,int b,int c){if(a<0^b<0){a=-a;p('-');}for(p(a/b+".");c>0;c--)p((a=a%b*10)/b);}<T>void p(T x){System.out.print(x);}

I had to improvise so that a or b could be -2147483648 as positive 32-bit integers only count towards 2147483647, that's why a became a long. There could be a better way of handling negative results, but I know none (doubles would probably get this to work for abs(a) < abs(b) as they have -0 but only ones' complement would keep the precision).

Why two byte numbers? I needed 92 bytes for the calculation and 36 for the print-helper (System.out.print sucks; generally Java isn't that golfy).

public class Div {

    void d(long a, int b, int c) {
        if (a < 0 ^ b < 0) {
            a = -a;
        for (p(a / b + "."); c > 0; c--) {
            p((a = a % b * 10) / b);

    <T> void p(T x) {

    public static void main(String[] args) {
        final Div div = new Div();
        div.d(12345, 234, 20);
        div.d(-12345, 234, 20);
        div.d(234, 234, 20);
        div.d(-234, 234, 20);
        div.d(234, 12345, 20);
        div.d(234, -12345, 20);
        div.d(-234, 12345, 20);
        div.d(-234, -12345, 20);
        div.d(-2147483648, 2147483647, 20);
        div.d(2147483647, -2147483648, 20);

The method basically exercises what most of us learned at school to generate the requested decimal digits.

share|improve this answer
Official ruling: I would say that ignoring Integer.MIN_VALUE is not okay but that long as input is fine. – durron597 Feb 26 '14 at 10:38
That's a lot shorter. Nicely done. – durron597 Feb 26 '14 at 11:24
@durron597 thank you. Still the strict typing and System.out make Java feel bulky ;-) Still a good feeling, that there already are longer answers posted. – TheConstructor Feb 26 '14 at 11:29
@durron597 you specifically asked for a function so I tought it would not count. If I had to use imports than probably yes. – TheConstructor Feb 26 '14 at 11:34
At least there is no $ to every variable ;-) – TheConstructor Feb 26 '14 at 17:45

C, 98 95 89


prints c digits after the .

example output:





should work for -2147483647<=a<=2147483647, same for b. handling the - was a pain.

online version: ideone

share|improve this answer
Does this work for a being -2147483648? Don't know c compilers well enough to tell which integer-type is assigned to your parameters. – TheConstructor Feb 26 '14 at 10:56
thanks for pointing it out. it works correctly for -2147483647<=a<=2147483647, same for b. there's a problem when a=-2147483648 and b is positive due to a=-a. – izabera Feb 26 '14 at 11:22
I tried but eventually got essentially the same solution as you. You can save one character by realizing that printf("-") returns 1. – Thomas Feb 26 '14 at 13:50

PHP, 108

function d($a,$b,$c){$a*$b<0&&$a*=-print'-';for($p='.';$c--;$a.=0,print$i.$p,$p='')$a-=$b*$i=($a-$a%$b)/$b;}

It works by simply outputting the quotient of a / b during a loop of c steps, a becoming the remainder multiplied by 10 at each iteration.


share|improve this answer
Produces strange results when a or b are negative – TheConstructor Feb 26 '14 at 0:41
I fixed the bug for negative numbers. Thanks! – Razvan Feb 26 '14 at 0:51
Just found a 112 version of your code: function d($a,$b,$c){if($a*$b<0)$a*=-print'-';for($p='.';$c--;$a*=10,$p=''){$a-=$b*$i=($a‌​-$a%$b)/$b;echo$i.$p;}} see return value – TheConstructor Feb 26 '14 at 1:20
Thanks. I even updated your version and managed to win an extra 1 byte. – Razvan Feb 26 '14 at 6:51

Python 111

f=lambda a,b,c:'-'[a*b>=0:]+'%s'%reduce(lambda(d,r),c:(d%c*10,r+`d/c`+'.'[r!='':],),[abs(b)]*c,(abs(a),''))[-1]

This solution does not violates any of the stated rules.

share|improve this answer

C: 72 characters


It almost entirely does what it is supposed to do. However it will as some of the other answers here give wonky values or fail for d(-2147483648,b,c) and d(a,-2147483648,c) since the absolute value of -2147483648 is out of bounds for a 32-bit word.

share|improve this answer

C 83


Same Idea that I used in my python implementation

share|improve this answer
Very nice! However, it crashes on d(-2147483648,-1,10) – durron597 Feb 26 '14 at 13:16

Perl, no arithmetic, 274 bytes

This is Euclidean long division, likely to consume an unusual amount of memory. The closest it gets to math on floating-point numbers is in using bit operations to parse them.

sub di{($v,$i,$d,$e)=(0,@_);($s,$c,$j)=$i=~s/-//g;$s^=$d=~s/-//g;









share|improve this answer

Ruby, 178

def d(a,b,c)
    a=-a if n
    f=m<0?"."+"0"*(l-1)+g[0..c-l-1] : g[0..l]+"."+g[l+1..c-2]
    p n ? "-"+f : f

Online version for testing.

The trick is to multiply a with a pretty high number, so the result is just an integer multiple of the floating point operation. Then the point and the zeros have to be inserted at the right place in the resulting string.

share|improve this answer
Does this work for c bigger than 350? – durron597 Feb 25 '14 at 22:53
I tested it with c=1000 - the code gave me an answer, maybe I should check the actual result though... – David Herrmann Feb 25 '14 at 22:55
does g get beyond 64 bits for large c? Edit: I think you are implicitly using BigInteger here – durron597 Feb 25 '14 at 22:58
Err, g is a string, but before you call to_s you've created a number in memory that is beyond 64 bits in size – durron597 Feb 25 '14 at 23:00
That is understandable - and makes the task more challenging (and interesting)! Is it better to delete the answer or leave it for others to have an example of how not to implement the task? – David Herrmann Feb 25 '14 at 23:21

python 92 bytes:

def d(a,b,c):c-=len(str(a/b))+1;e=10**c;a*=e;a/=b;a=str(a);x=len(a)-c;return a[:x]+'.'+a[x:]

i think some more golfing is possible.....

share|improve this answer
does e get beyond 64 bits for large c? Edit: I think you are implicitly using BigInteger here. – durron597 Feb 25 '14 at 22:59
@durron597 i highly doubt that. It goes to BigInt(Long in python) but 2**45 is 48 bits. Is that enough presicion?? Also, python has NO primitives so... – Maltysen Feb 25 '14 at 23:00
If a=5 and c=400 then after e=10**c, in hex, the number is 333 digits long. It starts 8889e7dd7f43fc2f7900bc2eac756d1c4927a5b8e56bbcfc97d39bac6936e648180f47d1396bc90‌​5a47cc481617c7... this is more than 64 bits. – durron597 Feb 25 '14 at 23:06
@durron597 400... do i need that – Maltysen Feb 25 '14 at 23:08
Yes rule 3 says you need to support up to at least 500... I was trying to prevent this (imo trivial) solution. – durron597 Feb 25 '14 at 23:08

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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