Code-Golf:模数除法

时间:2010-06-10 03:11:46

标签: language-agnostic code-golf

挑战:

如果不使用您的语言提供的模数除法运算符,请编写一个程序,该程序将从用户获取两个整数输入,然后显示第一个数字模数除以第二个数字的结果。假设所有输入都是正数。

示例:

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

谁赢了:

如果您不知道Code Golf的工作原理,获胜者是以最少的字符编写此程序的人。

29 个答案:

答案 0 :(得分:95)

CSS:107个字符:)

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;
}

随附HTML:     <ol> <li></li> <li></li> <li></li> <!-- etc. --> </ol>

<强>输出:

Output http://img155.imageshack.us/img155/4643/modd.png

这在IE中不起作用(惊喜!)。

答案 1 :(得分:25)

J,10个字符

([-]*<.@%)

用法:

   10 ([-]*<.@%) 3
1

J,17个字符(输入为列表)

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

用法:

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

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

说明:

我拿了一个图腾柱把它变成笑脸,它起作用了。

答案 2 :(得分:25)

Golfscript,6 7 13 chars:

2*~/*-

用法(只输入golfscript的方式):

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

说明:

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

答案 3 :(得分:13)

RePeNt,5个字符

2?/*-

使用:

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

RePeNt是一种基于堆栈的玩具语言,我自己在反向波兰表示法(RPN)中输入每个操作符/命令/循环。当我整理一下时,我会释放翻译。

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

答案 4 :(得分:12)

Ruby(32):

p(a=gets.to_i)-a/(b=gets.to_i)*b

答案 5 :(得分:8)

当然我不会赢,但这里什么都没有:

<?php  
$a=readline("#1:");  
$b=readline("#2:");  
while($b<=$a)$a-=$b;  
echo "Result: $a";  

答案 6 :(得分:5)

我知道已有两个Ruby答案,但为什么不呢?以这种方式获得输入是一种不同的方法来敲掉几个字符。

Ruby 1.8.7 +,29个字符

a,n=*$*.map(&:to_i);p a-a*n/n
$ ruby a.rb 10 3
1

答案 7 :(得分:4)

Python:25个字符

与负数一致,与模数运算符相同。采用两个以逗号分隔的数字。

x,y=input()
print x-x/y*y

答案 8 :(得分:4)

C:52

main(a,b){scanf("%d%d",&a,&b);printf("%d",a-a/b*b);}

答案 9 :(得分:3)

Clojure:30个字符

#(if(>%2%1)%1(recur(-%1%2)%2)))

答案 10 :(得分:3)

Unefunge-98:14 13 22 chars

&:7p&:' \/*-.@

Unefunge是Funge-98的一维实例:http://quadium.net/funge/spec98.html

说明(命令&lt; - 解释[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.

代码测试是不完整的(但足够完整)Unefunge-98解释器我写的测试代码:

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 ()

答案 11 :(得分:2)

Ruby:36个字符

a,b=gets.split.map(&:to_i);p a-a/b*b

答案 12 :(得分:2)

JavaScript,11个字符

a-b*(0|a/b)

假设输入整数包含变量ab

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

答案 13 :(得分:2)

计划:38

(define(m a b)(- a(*(quotient a b)b)))

答案 14 :(得分:1)

Perl,33个字符

读取输入可能会进一步缩短。

($a,$b)=@ARGV;print$a-$b*int$a/$b

用法

$  perl -e "($a,$b)=@ARGV;print$a-$b*int$a/$b" 2457 766
   159

答案 15 :(得分:1)

PHP,49个字符

假设以script.php?a=27&b=7形式输入查询字符串并打开短标记:

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

(可以通过取出单引号将其缩短为4,但这会引发通知。)

如果启用了卑鄙register_globals,您可以将其归结为 25个字符

<?echo $a-(int)($a/$b)*b;

答案 16 :(得分:1)

的Java。只是为了好玩

假设s[0]s[1]ints。不确定这是否值得,但它有点乐趣。

请注意,这不会受到循环效果(大数字)的影响,但仅适用于整数。无论数字有多大,这个解决方案同样快速。提供的答案中有很大一部分会产生一个巨大的递归堆栈,或者如果givin说一个大数字和一个小的除数,则会产生无限长的时间。

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);
    }
}

答案 17 :(得分:1)

Bash,21个字符

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

答案 18 :(得分:1)

C,226个字符

迟到:我决定使用最少数量的字符,同时完全避免算术操作。相反,我使用文件系统来计算结果:

#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));}

答案 19 :(得分:0)

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);}}

注意程序确实有效,但它也会抛出

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

输入输入后和输出输出后

答案 20 :(得分:0)

Common Lisp,170个字符(包括缩进):

(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)))))))

旧版本(187个字符):

(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)))))

答案 21 :(得分:0)

DC:8个字符

odO/O*-p

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

答案 22 :(得分:0)

Java,110个字符

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);}}

答案 23 :(得分:0)

Rebmu:10个字符(无I / O)和15个字符(带I / O)

如果I / O不是程序源的一部分,并且您愿意传入命名参数,那么我们可以得到10个字符:

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

如果需要I / O,则将其带到15:

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

但是使用乘法和除法并不像这个17个字符的解决方案那样有趣(或效率低):

rJrKwWGEjK[JsbJk]

引擎盖下的东西变成了等同物:

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
)

答案 24 :(得分:0)

Perl 25个字符

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

用法:

echo 15 6 | perl modulo.pl
3

答案 25 :(得分:0)

Haskell,30个字符

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

这是我的第一个代码高尔夫,可以自由评论代码和发布改进。 ; - )

我知道我不会赢,但我只想用列表分享我的解决方案。

答案 26 :(得分:0)

红宝石中有38个字符 p (a=gets.to_i)-((b=gets.to_i)*(a/b))
不是赢家:(

答案 27 :(得分:0)

DC:7个Chars(可能是5;)

??37axp

使用如下:

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

[并且,参考上面的其他一些例子,如果允许将输入插入代码中,它可以是5个字符:

37axp

如:

dc -e "17 3 37axp"

只是觉得值得一提]

答案 28 :(得分:-1)

F#,268个字符

我赢了吗?

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
相关问题