1898

29
+16  Q:

## Code-Golf: Modulus Divide

Challenge:

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.

Example:

``````    Input of first number:2
Input of second number:2
Result:0
``````

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:

``````<?php
while(\$b<=\$a)\$a-=\$b;
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;`
27 if you skip the echo: `<?while(\$b<=\$a-=\$b)?><?=\$a;`
+3  A:

## Ruby: 36 chars

``````a,b=gets.split.map(&:to_i);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]);
System.out.println(a-a/b*b);
}
}
``````
what language is that, pls indicate
Looks to be java
It is Java.` ` ` `
+12  A:

## Ruby (32):

``````p(a=gets.to_i)-a/(b=gets.to_i)*b
``````
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.
+4  A:

## Python: 25 chars

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

``````x,y=input()
print x-x/y*y
``````
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.
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
+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
1
```
+4  A:

# C: 52

``````main(a,b){scanf("%d%d",&a,&b);printf("%d",a-a/b*b);}
``````
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.
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: 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:

``````<?echo(\$a=\$_GET['a'])-(int)(\$a/\$b=\$_GET['b'])*\$b;
``````

(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;`
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)))
``````
+24  A:

## J, 10 characters

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

Usage:

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

## J, 17 characters (with input as a list)

``````({.-{:*[:<.{.%{:)
``````

Usage:

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

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

Explanation:

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

Ahhh J.... Why do we even bother?
@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.
+1 for properly explaining your code
+4  A:

## Clojure: 30 characters

``````#(if(>%2%1)%1(recur(-%1%2)%2)))
``````
+24  A:

# Golfscript, 6 713 chars:

``````2*~/*-
``````

Usage (only way to input into golfscript):

``````echo 14 3 | ruby golfscript.rb modulo.gs
2
``````

Explanation:

``````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 modulo.gs` different to `golfscript modulo.gs`, 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
This should be above J
Everything should be above J.
@Claudiu: have fun with that C interpreter in python :)
A:

# 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
``````

### Usage

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

# Unefunge-98: 14 1322 chars

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

Unefunge is the 1-dimensional instance of Funge-98: http://quadium.net/funge/spec98.html

Explanation (Command <- Explaination [Stack]):

``````& <- Get integer input of value A and store on stack.
[A]
: <- 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).
[A]
& <- 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.
[(A-(B*(A/B)))]
. <- 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 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
'-' -> 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
where
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)
where
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'}
where
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
where
b = topStack env
a = topStack \$ popStack env

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
where
(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."
exitFailure
fileName:_ -> return \$ Args { sourceFileName = fileName }

runUnefunge :: Env -> IO ExitCode
runUnefunge = iterateM round . return
where
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>`

Output:

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

Consider my mind blown
That is so awesome.
Wow. I am literally lost for words.
Pretty clever :)
Now that is thinking outside the box model!
+3  A:

## JavaScript, 11 chars

``````a-b*(0|a/b)
``````

Assumes input integers are contained the variables `a` and `b`:

``````a = 2;
b = 2;
``````
A:

# Java: 127 Chars

``````import java.util.*;enum M{M;M(){Scanner s=new Scanner(System.in);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

``````2?/*-
``````

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
``````
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: http://stackoverflow.com/questions/232861/fibonacci-code-golf/3029192#3029192 and the J winner on the same page.
*I meant golfscript winner
A:

Common Lisp, 170 chars (including indentation):

``````(defun mod-divide()
(let*((a(g"first"))(b(g"second")))
(format t "Result:~d~%"(- a(* b(truncate a b)))))))
``````

Old version (187 characters):

``````(defun mod-divide()
(let*((a(g"first"))(b(g"second")))
(multiple-value-bind(a b)(truncate a b)(format t "Result:~d~%"b)))))
``````
A:

# Bash, 21 chars

``````echo \$((\$1-\$1/\$2*\$2))
``````
A:

## DC: 8 chars

`odO/O*-p`

``````\$ echo '17 3 odO/O*-p' | dc
2
``````
A:

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);}}
``````
A:

## 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
3
``````

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

``````rJrKwWGEjK[JsbJk]
``````

Which under the hood is turned into the equivalent:

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

Documented:

``````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
)
``````
For a bigger problem solved in this language, see: http://stackoverflow.com/questions/3034331/code-golf-rotating-maze/3060396#3060396
+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));}
``````
+2  A:

Perl 25 characters

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

usage:

``````echo 15 6 | perl modulo.pl
3
``````
A:

``````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.

A:

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

A:

## DC: 7 Chars (maybe 5 ;)

``````??37axp
``````

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:

``````37axp
``````

as in:

``````dc -e "17 3 37axp"
``````

Just thought it worth a mention]