views:

1898

answers:

29

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  
$a=readline("#1:");  
$b=readline("#2:");  
while($b<=$a)$a-=$b;  
echo "Result: $a";  
Fosco
+1 for providing a solution in a less-commonly-code-golfed language.
Russell
You can knock off a few chars with short tags and removing newlines.
waiwai933
How many characters is that? I am to lazy to count.
thyrgle
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;`
Morningcoffee
+3  A: 

Ruby: 36 chars

a,b=gets.split.map(&:to_i);p a-a/b*b
zed_0xff
+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);
    }
}
Josh K
what language is that, pls indicate
Nas Banov
Looks to be java
Graphain
It is Java.` ` ` `
Josh K
+12  A: 

Ruby (32):

p(a=gets.to_i)-a/(b=gets.to_i)*b
Fat Lotus
this will not output any result, you have to add "p " at start
zed_0xff
Why the downvotes? This is community wiki--just add the missing p, add one to the count, and it's correct.
Jordan
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.

x,y=input()
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`.
Thanatos
Wasn't counting spaces it seems.
Dominic Bou-Samra
Sorry to lose you 1. ;-) Bartender! I owe this man an octet!
Thanatos
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
1
Mark Rushakoff
+4  A: 

C: 52

main(a,b){scanf("%d%d",&a,&b);printf("%d",a-a/b*b);}
Jerry Coffin
Oh, you horrible person... what have you done to my `main`... ;-)
Thanatos
It works without the space in the scanf format string (for me at least).
dreamlax
@dreamlax:good point. Thanks.
Jerry Coffin
why bother scanfing? You may as well take the input as args.
Cam
@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. :)
Cam
+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;
Jordan
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
Kevin
+3  A: 

Scheme: 38

(define(m a b)(- a(*(quotient a b)b)))
Jerry Coffin
+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.

David
Ahhh J.... Why do we even bother?
Dominic Bou-Samra
@Dominic: Beats me, you should learn J! :)
David
golfscript ftw !
Claudiu
It looks like a mostly happy crowd of faces one way, and another way it looks like a mostly sad crowd of faces.
dreamlax
@dreamlax: And yet it's funny how out of all of the sad faces, the one on the bottom is the happiest.
David
"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
Anax
+4  A: 

Clojure: 30 characters

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

Golfscript, 6 7 13 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
Claudiu
insane, I need to learn GolfScript and J
Anurag
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
@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.
Claudiu
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...
Skizz
...'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
@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.
Claudiu
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.
trinithis
+1 for beating J
BlueRaja - Danny Pflughoeft
This should be above J
Callum Rogers
Everything should be above J.
JUST MY correct OPINION
@Claudiu: have fun with that C interpreter in python :)
RCIX
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
Brian
Sorry, you didn't.
thyrgle
+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
Zaid
use `say` instead of `print` :)
azatoth
+4  A: 

Unefunge-98: 14 13 22 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 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
  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

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
  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 ()
trinithis
I wonder how compact you could get a Befunge-98 version.
JAB
I tried it with Befunge-98 but could not figure out the put `p` command. What's the purpose of `p` around `7p` there?
Anurag
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.
trinithis
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 :(
trinithis
Fixed. (filler)
trinithis
+1 thanks for the detailed explanation.
Anurag
+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:

Output

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

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

JavaScript, 11 chars

a-b*(0|a/b)

Assumes input integers are contained the variables a and b:

a = 2;
b = 2;
alert(a-b*(0|a/b)); // => 0
J-P
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.

trinithis
+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
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)
Claudiu
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.
Callum Rogers
*I meant golfscript winner
Callum Rogers
A: 

Common Lisp, 170 chars (including indentation):

(defun mod-divide()
  (flet((g(p)(format t"Input of ~a number:"p)(read)))
    (let*((a(g"first"))(b(g"second")))
      (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)))
    (let*((a(g"first"))(b(g"second")))
      (multiple-value-bind(a b)(truncate a b)(format t "Result:~d~%"b)))))
Vatine
A: 

Bash, 21 chars

echo $(($1-$1/$2*$2))
azatoth
A: 

DC: 8 chars

odO/O*-p

$ echo '17 3 odO/O*-p' | dc
2
Geoff Reedy
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);}}
Robert Tuck
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
)
Hostile Fork
For a bigger problem solved in this language, see: http://stackoverflow.com/questions/3034331/code-golf-rotating-maze/3060396#3060396
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$`/$'

usage:

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

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.

tomp
A: 

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

Gerhard
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]

Hiato