挑战:
在不使用您的语言已经提供的模除运算符的情况下,编写一个程序,该程序将接受来自用户的两个整数输入,然后显示第一个数模除数除以第二个数的结果。假设所有输入都是正数。
例子:
Input of first number:2
Input of second number:2
Result:0
谁赢:
如果您不知道 Code Golf 是如何工作的,那么获胜者就是以最少的字符编写此程序的人。
挑战:
在不使用您的语言已经提供的模除运算符的情况下,编写一个程序,该程序将接受来自用户的两个整数输入,然后显示第一个数模除数除以第二个数的结果。假设所有输入都是正数。
例子:
Input of first number:2
Input of second number:2
Result:0
谁赢:
如果您不知道 Code Golf 是如何工作的,那么获胜者就是以最少的字符编写此程序的人。
CSS(非高尔夫球):
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>
输出:
输出 http://img155.imageshack.us/img155/4643/modd.png
这在 IE 中不起作用(惊喜!)。
([-]*<.@%)
用法:
10 ([-]*<.@%) 3
1
({.-{:*[:<.{.%{:)
用法:
({.-{:*[:<.{.%{:) 10 3
1
({.-{:*[:<.{.%{:) 225 13
4
解释:
我拿了一根图腾柱,把它变成了一个笑脸,它奏效了。
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
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
p(a=gets.to_i)-a/(b=gets.to_i)*b
当然我不会赢,但这里什么都没有:
<?php
$a=readline("#1:");
$b=readline("#2:");
while($b<=$a)$a-=$b;
echo "Result: $a";
我知道已经有两个 Ruby 答案,但为什么不呢?以这种方式获取输入是一种足够不同的方法来敲掉几个字符。
a,n=*$*.map(&:to_i);p a-a*n/n
$红宝石 a.rb 10 3 1
main(a,b){scanf("%d%d",&a,&b);printf("%d",a-a/b*b);}
对负数表现,与模运算符相同。接受两个逗号分隔的数字。
x,y=input()
print x-x/y*y
#(if(>%2%1)%1(recur(-%1%2)%2)))
&:7p&:' \/*-.@
Unefunge 是 Funge-98 的一维实例:http: //quadium.net/funge/spec98.html
说明(命令 <- 说明 [堆栈]):
& <- 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 ()
(define(m a b)(- a(*(quotient a b)b)))
a,b=gets.split.map(&:to_i);p a-a/b*b
a-b*(0|a/b)
假设输入整数包含变量a
和b
:
a = 2;
b = 2;
alert(a-b*(0|a/b)); // => 0
假设查询字符串输入的形式script.php?a=27&b=7
和短标签打开:
<?echo($a=$_GET['a'])-(int)($a/$b=$_GET['b'])*$b;
(通过去掉单引号可以缩短四,但这会引发通知。)
打开邪恶register_globals
后,您可以将其减少到25 个字符:
<?echo $a-(int)($a/$b)*b;
迟到:我决定尽量减少字符数,同时完全避免算术运算。相反,我使用文件系统来计算结果:
#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));}
假设s[0]
和s[1]
是ints
。不确定这是否值得,但它有点有趣。
请注意,这不会受到循环效应(大数)的影响,但仅适用于整数。同样,无论数字有多大,这个解决方案都同样快。提供的大部分答案将生成一个巨大的递归堆栈,或者如果给出一个很大的数字和一个小的除数,则需要无限长的时间。
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);
}
}
echo $(($1-$1/$2*$2))
读取输入可能会进一步缩短。
($a,$b)=@ARGV;print$a-$b*int$a/$b
$ perl -e "($a,$b)=@ARGV;print$a-$b*int$a/$b" 2457 766
159
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);}}
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
在输入输入之后和输出输出之后。
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)))))
如果程序源不需要 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
)
odO/O*-p
$ echo '17 3 odO/O*-p' | dc
2
m a b=a-last((a-b):[b,2*b..a])
这是我的第一个代码高尔夫,可以自由评论代码并发布改进。;-)
我知道我不会赢,但我只是想用列表分享我的解决方案。
Perl 25 个字符
<>=~/ /;say$`-$'*int$`/$'
用法:
echo 15 6 | perl modulo.pl
3
??37axp
使用如下:
echo "X\nY" | dc -e "??37axp"
[并且,参考上面的一些其他示例,如果允许在代码中插入输入,则可以是 5 个字符:
37axp
如:
dc -e "17 3 37axp"
只是觉得值得一提]
在 38 个字符的红宝石中
p (a=gets.to_i)-((b=gets.to_i)*(a/b))
不是赢家 :(
我赢了吗?
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