Without using the modulus divide operator provided already by your language, write a program that will take two integer inputs from a user and then displays the result of the first number modulus divided number by the second number. Assume all input is positive.


    Input of first number:2
    Input of second number:2

Who wins:

In case you don't know how Code Golf works, the winner is the person who writes this program in the least amount of characters.

+9  A: 

Sure I won't win, but here goes nothing:

echo "Result: $a";  
+1 for providing a solution in a less-commonly-code-golfed language.
You can knock off a few chars with short tags and removing newlines.
How many characters is that? I am to lazy to count.
28 if you use GET variables with register_globals`: `<?while($b<=$a-=$b);echo $a;`
Casey Hope
27 if you skip the echo: `<?while($b<=$a-=$b)?><?=$a;`
+3  A: 

Ruby: 36 chars

a,;p a-a/b*b
+2  A: 

Java. Just for fun

Assuming that s[0] and s[1] are ints. Not sure this is worth anything but it was a bit of fun.

Note that this won't suffer from the loop effect (large numbers) but will only work on whole numbers. Also this solution is equally fast no matter how large the numbers are. A large percentage of the answers provided will generate a huge recursive stack or take infinitely long if givin say a large number and a small divisor.

public class M
    public static void main(String [] s)
        int a = Integer.parseInt(s[0]);
        int b = Integer.parseInt(s[1]);
Josh K
what language is that, pls indicate
Nas Banov
Looks to be java
It is Java.` ` ` `
Josh K
+12  A: 

Ruby (32):

Fat Lotus
this will not output any result, you have to add "p " at start
Why the downvotes? This is community wiki--just add the missing p, add one to the count, and it's correct.
yah people, don't down vote this, he is offering his solution to a code gold question... live respect here.
Joseph Silvashy
+4  A: 

Python: 25 chars

Behaves with negative numbers, identically to modulus operator. Takes two comma-separated numbers.

print x-x/y*y
Dominic Bou-Samra
32? Are you sure? `echo -n "i=input;x=i();y=i();print x-x/y*y" | wc -c` gives me `33`. `cat your_program | my_eye` also gives `33`.
Wasn't counting spaces it seems.
Dominic Bou-Samra
Sorry to lose you 1. ;-) Bartender! I owe this man an octet!
new lines are counted as at least 1 char, so it does not matter if it's ';' or new line
Nas Banov
+6  A: 

I know there's already two Ruby answers, but why not; getting the input this way is a different enough approach to knock off a few characters.

Ruby 1.8.7+, 29 chars

a,n=*$*.map(&:to_i);p a-a*n/n
$ ruby a.rb 10 3
Mark Rushakoff
+4  A: 

C: 52

Jerry Coffin
Oh, you horrible person... what have you done to my `main`... ;-)
It works without the space in the scanf format string (for me at least).
@dreamlax:good point. Thanks.
Jerry Coffin
why bother scanfing? You may as well take the input as args.
@incrediman: because at least as I read it, taking the input from the user is supposed to be part of the program. In any case, I'm not sure taking them on the command line would make it any shorter...
Jerry Coffin
@Jerry: Ah, yes. Nevermind - I didn't realize it had to be direct user input. I suppose that makes sense. :)
+2  A: 

PHP, 49 chars

Assuming query string input in the form of script.php?a=27&b=7 and short tags turned on:


(That could be shortened by four by taking out the single-quotes, but that would throw notices.)

With the vile register_globals turned on you can get it down to 25 chars:

<?echo $a-(int)($a/$b)*b;
With equally vile short tags you could get it down even more: `<?=$a-(int)($a/$b)*$b;`
Casey Hope
Assume CLI instead of web access and get this approach to 44 with: list($x,$a,$b)=$argv;echo$a-(int)($a/$b)*$b; // Usage is php -r 'list($x,$a,$b)=$argv;echo$a-(int)($a/$b)*$b;' 225 13
+3  A: 

Scheme: 38

(define(m a b)(- a(*(quotient a b)b)))
Jerry Coffin
+24  A: 

J, 10 characters

([-]*<[email protected]%)


   10 ([-]*<[email protected]%) 3

J, 17 characters (with input as a list)



  ({.-{:*[:<.{.%{:) 10 3

  ({.-{:*[:<.{.%{:) 225 13


I took a totem pole and turned it into a smiley, and it worked.

Ahhh J.... Why do we even bother?
Dominic Bou-Samra
@Dominic: Beats me, you should learn J! :)
golfscript ftw !
It looks like a mostly happy crowd of faces one way, and another way it looks like a mostly sad crowd of faces.
@dreamlax: And yet it's funny how out of all of the sad faces, the one on the bottom is the happiest.
"I took a totem pole and turned it into a smiley, and it worked." Gold sir, gold.
Sam Pearson
+1 for properly explaining your code
+4  A: 

Clojure: 30 characters

Greg Harman
+24  A: 

Golfscript, 6 7 13 chars:


Usage (only way to input into golfscript):

echo 14 3 | ruby golfscript.rb


2*~     #double the input string and eval (so now 14 3 14 3 are on the stack)
/       #int divide 14 / 3, gives quotient
*-      #multiply that result by 3, subtract from 14, gives remainder
insane, I need to learn GolfScript and J
Surely you should include the contents of golfscript.rb? I mean, I could write a .rb file (called, modulo.rb) which implements the modulo language thus: the symbol 'm' returns the modulo of the first two parameters given on stdin and outputs result to stdout. Therefore, my new language fulfils the criteria and is does so in one character!
@Skizz: yes but your language would only solve the modulo problem. golfscript has solved dozens of code golf challenges, and i believe it is Turing-complete, meaning you could really write any program in it. just because it is simple to implement it in ruby doesn't mean i need to include the implementation - that's like saying you should put include the source of GCC for any C program.
Your GCC example isn't quite the same. A better example would be to include contents of, say, "stdio.h" as part of the C program. And of course, how do you cope with linking to external libraries? Let's say the 'm' function was defined in a library which is linked into the final executable, should it be included. If so, should the IO routines be included (because an assembler version would have that included). Anyway. I'm not being totally serious here, I just never realised that, in this case at least, GS was a Ruby program which blurs the line between 'program' and 'code' where...
...'program' is all the code needed to accomplish the given task and 'code' is the bit you've written. Is `ruby golfscript.rb` different to `golfscript`, the latter not needing the Ruby environment and is its own environment.
@Skizz: heh ya i realize it's half-serious, but it's an interesting philosophical question. if golfscript requires the ruby code, then I'm going to write a C interpreter in Python and require your C code to include my interpreter =P. I think the key is that a language isn't defined by its implementation (say `golfscript.rb` or the gcc compiler), but by its spec. also, your `m` function exists, and it's called `%` =P.
Lisp already blurs the line between program and code :D. If the whole golfscript.rb is such an issue, writing and compiling a GolfScript interpreter/compiler as a standalone program should be trivial anyway.
+1 for beating J
BlueRaja - Danny Pflughoeft
This should be above J
Callum Rogers
Everything should be above J.
@Claudiu: have fun with that C interpreter in python :)

F#, 268 chars

Did I win?

printf "Input of first number:"
let x = stdin.ReadLine() |> int
printf "Input of second number:"
let y = stdin.ReadLine() |> int
let mutable z = x
while z >= 0 do
    z <- z - y
// whoops, overshot
z <- z + y
// I'm not drunk, really
printfn "Result:%d" z
Sorry, you didn't.
+2  A: 

Perl, 33 chars

Reading the inputs could probably be shortened further.

($a,$b)[email protected];print$a-$b*int$a/$b


$  perl -e "($a,$b)[email protected];print$a-$b*int$a/$b" 2457 766
use `say` instead of `print` :)
+4  A: 

Unefunge-98: 14 13 22 chars

&:7p&:' \/*[email protected]

Unefunge is the 1-dimensional instance of Funge-98:

Explanation (Command <- Explaination [Stack]):

& <- Get integer input of value A and store on stack.
: <- Duplicate top of stack.
     [A A]
7 <- Push 7 on stack. Used for the `p` command.
     [A A 7]
p <- Pop top two values (7 then A). Place the character whose ASCII value 
     is A at position 7 in the code (where the space is).
& <- Get integer input of value B and store on stack.
     [A B]
: <- Duplicate top of stack.
     [A B B]
' <- Jump over next character and grap the ASCII value of the jumped character.
     [A B B A]
  <- Because of the `p` command, this is actually the character whose ASCII
     value is A at this point in the code. This was jumped over by the 
     previous instruction.
\ <- Swap top two values of stack.
     [A B A B]
/ <- Pop top two values (B then A). Push (A/B) (integer division) onto stack.
     [A B (A/B)]
* <- Pop top two values ((A/B) then B). Push (B*(A/B)) onto stack.
     [A (B*(A/B))]
- <- Pop top two values ((B*(A/B)) then A). Push (A-(B*(A/B))) onto stack.
. <- Pop top value and print it as an integer.
@ <- Exit program.

Code tested is this incomplete (but complete enough) Unefunge-98 interpreter I wrote to test the code:

module Unefunge where

import Prelude hiding (subtract)

import qualified Data.Map as Map

import Control.Exception (handle)
import Control.Monad

import Data.Char (chr, ord)
import Data.Map (Map)

import System.Environment (getArgs)
import System.Exit (exitSuccess, exitFailure, ExitCode (..))
import System.IO (hSetBuffering, BufferMode (..), stdin, stdout)


iterateM :: (Monad m) => (a -> m a) -> m a -> m b
iterateM f m = m >>= iterateM f . f


data Cell = Integer Integer | Char Char


newtype Stack = Stack [Integer]

mkStack = Stack []

push :: Integer -> Stack -> Stack
push x (Stack xs) = Stack (x : xs)

pop :: Stack -> Stack
pop (Stack xs) = case xs of
  []   -> Stack []
  _:ys -> Stack ys

top :: Stack -> Integer
top (Stack xs) = case xs of
  []  -> 0
  y:_ -> y


data Env = Env {
    cells :: Map Integer Cell
  , position :: Integer
  , stack :: Stack

withStack :: (Stack -> Stack) -> Env -> Env
withStack f env = env { stack = f $ stack env }

pushStack :: Integer -> Env -> Env
pushStack x = withStack $ push x

popStack :: Env -> Env
popStack = withStack pop

topStack :: Env -> Integer
topStack = top . stack


type Instruction = Env -> IO Env

cellAt :: Integer -> Env -> Cell
cellAt n = Map.findWithDefault (Char ' ') n . cells

currentCell :: Env -> Cell
currentCell env = cellAt (position env) env

lookupInstruction :: Cell -> Instruction
lookupInstruction cell = case cell of
  Integer n -> pushInteger n
  Char c -> case c of
    '\''-> fetch
    '\\'-> swap
    '0' -> pushInteger 0
    '1' -> pushInteger 1
    '2' -> pushInteger 2
    '3' -> pushInteger 3
    '4' -> pushInteger 4
    '5' -> pushInteger 5
    '6' -> pushInteger 6
    '7' -> pushInteger 7
    '8' -> pushInteger 8
    '9' -> pushInteger 9
    ' ' -> nop
    '+' -> add
    '-' -> subtract
    '*' -> multiply
    '/' -> divide
    '#' -> trampoline
    '&' -> inputDecimal
    '.' -> outputDecimal
    ':' -> duplicate
    'p' -> put
    '@' -> stop

instructionAt :: Integer -> Env -> Instruction
instructionAt n = lookupInstruction . cellAt n

currentInstruction :: Env -> Instruction
currentInstruction = lookupInstruction . currentCell

runCurrentInstruction :: Instruction
runCurrentInstruction env = currentInstruction env env

nop :: Instruction
nop = return

swap :: Instruction
swap env = return $ pushStack a $ pushStack b $ popStack $ popStack env
    b = topStack env
    a = topStack $ popStack env

inputDecimal :: Instruction
inputDecimal env = readLn >>= return . flip pushStack env

outputDecimal :: Instruction
outputDecimal env = putStr (show n ++ " ") >> return (popStack env)
    n = topStack env

duplicate :: Instruction
duplicate env = return $ pushStack (topStack env) env

pushInteger :: Integer -> Instruction
pushInteger n = return . pushStack n

put :: Instruction
put env = return env' { cells = Map.insert loc c $ cells env'}
    loc = topStack env
    n = topStack $ popStack env
    env' = popStack $ popStack env
    c = Char . chr . fromIntegral $ n

trampoline :: Instruction
trampoline env = return env { position = position env + 1 }

fetch :: Instruction
fetch = trampoline >=> \env -> let
  cell = currentCell env
  val = case cell of
    Char c -> fromIntegral $ ord c
    Integer n -> n
  in pushInteger val env

binOp :: (Integer -> Integer -> Integer) -> Instruction
binOp op env = return $ pushStack (a `op` b) $ popStack $ popStack env
    b = topStack env
    a = topStack $ popStack env

add :: Instruction
add = binOp (+)

subtract :: Instruction
subtract = binOp (-)

multiply :: Instruction
multiply = binOp (*)

divide :: Instruction
divide = binOp div

stop :: Instruction
stop = const exitSuccess

tick :: Instruction
tick = trampoline


buildCells :: String -> Map Integer Cell
buildCells = Map.fromList . zip [0..] . map Char . concat . eols

eols :: String -> [String]
eols "" = []
eols str = left : case right of
  "" -> []
  '\r':'\n':rest -> eols rest
  _:rest -> eols rest
    (left, right) = break (`elem` "\r\n") str

data Args = Args { sourceFileName :: String }

processArgs :: IO Args
processArgs = do
  args <- getArgs
  case args of
    [] -> do
      putStrLn "No source file! Exiting."
    fileName:_ -> return $ Args { sourceFileName = fileName }

runUnefunge :: Env -> IO ExitCode
runUnefunge = iterateM round . return
    round = runCurrentInstruction >=> tick

main :: IO ()
main = do
  args <- processArgs
  contents <- readFile $ sourceFileName args
  let env = Env {
      cells = buildCells contents
    , position = 0
    , stack = mkStack
  mapM_ (`hSetBuffering` NoBuffering) [stdin, stdout]
  handle return $ runUnefunge env
  return ()
I wonder how compact you could get a Befunge-98 version.
I tried it with Befunge-98 but could not figure out the put `p` command. What's the purpose of `p` around `7p` there?
The code is incompatable with Befunge-98. The `p` command differs based on the dimensionality of the funge (Unefunge=1 Befunge=2). I'll write an explanation of what the code does.
Ah, I have a small bug in addition. `p` doesn't store the integer value there, it stores the character value there. I'll have to add one character to my code to remedy that :(
Fixed. (filler)
+1 thanks for the detailed explanation.
+90  A: 

CSS: 107 chars :)

CSS (ungolfed):

li {
    counter-increment: a;

li:after {
    content: counter(a);

li:nth-child(3n) { /* replace 3 with 2nd input ("b" in "a % b") */
    counter-reset: a;
    counter-increment: none;

Accompanying HTML: <ol> <li></li> <li></li> <li></li> <!-- etc. --> </ol>



This doesn't work in IE (surprise surprise!).

Casey Hope
Consider my mind blown
That is so awesome.
Joe D
Wow. I am literally lost for words.
Callum Rogers
Pretty clever :)
Now that is thinking outside the box model!
John Rasch
+3  A: 

JavaScript, 11 chars


Assumes input integers are contained the variables a and b:

a = 2;
b = 2;
alert(a-b*(0|a/b)); // => 0

Java: 127 Chars

import java.util.*;enum M{M;M(){Scanner s=new Scanner(;int a=s.nextInt(),b=s.nextInt();System.out.println(a-a/b*b);}}

Note the program does work, but it also throws

Exception in thread "main" java.lang.NoSuchMethodError: main

after the inputs are entered and after the output is outputted.

+13  A: 

RePeNt, 5 chars


Run using:

RePeNt mod.rpn 17 3
RePeNt "2?/*-" 17 3

RePeNt is a stack-based toy language I made myself where every operator/command/loop is entered in Reverse Polish Notation (RPN). I will release the interpreter when I have tidied it up a bit.

Command      Explanation                                              Stack
-------      -----------                                              -----

n/a          The program takes 2 parameters ( 17 3 ) and pushes them  17 3
             onto the stack
2            Pushes a 2 onto the stack                                17 3 2
?            Pops a number (x) off the stack + copies the last x      17 3 17 3
             stack items onto the stack
/            Divides on stack                                         17 3 5
*            Multiplies on stack                                      17 15
-            Subtracts on stack                                       2
Callum Rogers
i think RePeNt already exists, and is called GolfScript? the operators seem to work the same way. th e only diff between our programs is that you don't need to initially eval your arguments (`~` in gs)
They are very similar, I think (I have never written anything in GolfScript, only read the spec) in that they are both stack based languages - you could say C# and C++ are the same as they both have types and use infix notation. My language and GolfScript have important differences, especially with respect to variables, custom types and control flows (none of which have been used here). It is really a mixture of J and Golfscript. Solutions can be significantly different, like: and the J winner on the same page.
Callum Rogers
*I meant golfscript winner
Callum Rogers

Common Lisp, 170 chars (including indentation):

(defun mod-divide()
  (flet((g(p)(format t"Input of ~a number:"p)(read)))
      (format t "Result:~d~%"(- a(* b(truncate a b)))))))

Old version (187 characters):

(defun mod-divide()
  (flet((g(p)(format t"Input of ~a number:"p)(read)))
      (multiple-value-bind(a b)(truncate a b)(format t "Result:~d~%"b)))))

Bash, 21 chars

echo $(($1-$1/$2*$2))

DC: 8 chars


$ echo '17 3 odO/O*-p' | dc
Geoff Reedy

Java, 110 chars

class C{public static void main(String[]a){Long x=new Long(a[0]),y=x.decode(a[1]);System.out.print(x-x/y*y);}}
Robert Tuck

Rebmu: 10 chars (no I/O) and 15 chars (with I/O)

If I/O is not required as part of the program source and you're willing to pass in named arguments then we can get 10 characters:

>> rebmu/args [sbJmpDVjKk] [j: 20 k: 7]
== 6

If I/O is required then that takes it to 15:

>> rebmu [rJrKwSBjMPdvJkK]
Input Integer: 42
Input Integer: 13

But using multiplication and division isn't as interesting (or inefficient) as this 17-character solution:


Which under the hood is turned into the equivalent:

r j r k w wge j k [j: sb j k]


r j ; read j from user
r k ; read k from user

; write out the result of...
w (
    ; while j is greater than or equal to k
    wge j k [
        ; assign to j the result of subtracting k from j
        j: sb j k

    ; when a while loop exits the expression of the while will have the
    ; value of the last calculation inside the loop body.  In this case,
    ; that last calculation was an assignment to j, and will have the 
    ; value of j
Hostile Fork
For a bigger problem solved in this language, see:
Hostile Fork
+2  A: 

C, 226 chars

Late entry: I decided to go for the least number of characters while avoiding arithmetic operations altogether. Instead, I use the file system to compute the result:

#include <stdio.h>
#define z "%d"
#define y(x)x=fopen(#x,"w");
#define g(x)ftell(x)
#define i(x)fputs(" ",x);
main(a,b){FILE*c,*d;scanf(z z,&a,&b);y(c)y(d)while(g(c)!=a){i(c)i(d)if(g(d)==b)fseek(d,0,0);}printf(z,g(d));}
Blair Holloway
+2  A: 

Perl 25 characters

<>=~/ /;say$`-$'*int$`/$'


echo 15 6 | perl

Haskell, 30 chars

m a b=a-last((a-b):[b,2*b..a])

This is my first code golf, be free to comment on code and post improvements. ;-)

I know I won't win, but I just wanted to share my solution using lists.


In ruby with 38 chars
p (a=gets.to_i)-((b=gets.to_i)*(a/b))
Not a winner :(


DC: 7 Chars (maybe 5 ;)


Used as follows:

echo "X\nY" | dc -e "??37axp"

[And, referencing some other examples above, if input is allowed to be inserted into the code, it can be 5 chars:


as in:

dc -e "17 3 37axp"

Just thought it worth a mention]