20

チャレンジ:

すでに使用している言語で提供されているモジュラス除算演算子を使用せずに、ユーザーから2つの整数入力を受け取り、最初の数値のモジュラス除算数を2番目の数値で割った結果を表示するプログラムを作成します。すべての入力が正であると想定します。

例:

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

誰が勝ちますか:

コードゴルフがどのように機能するかわからない場合、勝者はこのプログラムを最も少ない文字数で書いた人です。

4

29 に答える 29

95

CSS: 107 文字 :)

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 では機能しません (驚きの驚き!)。

于 2010-06-10T19:52:02.190 に答える
25

Golfscript、6 7 13文字:

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
于 2010-06-10T04:30:36.293 に答える
25

J、10文字

([-]*<.@%)

使用法:

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

J、17文字(リスト入力あり)

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

使用法:

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

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

説明:

トーテムポールをスマイリーに変えてみたらうまくいきました。

于 2010-06-10T03:58:55.367 に答える
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
于 2010-06-12T12:32:28.167 に答える
12

ルビー (32):

p(a=gets.to_i)-a/(b=gets.to_i)*b
于 2010-06-10T03:22:06.867 に答える
8

確かに私は勝てませんが、ここでは何も起こりません:

<?php  
$a=readline("#1:");  
$b=readline("#2:");  
while($b<=$a)$a-=$b;  
echo "Result: $a";  
于 2010-06-10T03:19:14.140 に答える
5

すでに 2 つの Ruby の回答があることは知っていますが、それはなぜでしょうか。この方法で入力を取得することは、いくつかの文字をノックアウトするのに十分な別のアプローチです。

Ruby 1.8.7+、29 文字

a,n=*$*.map(&:to_i);p a-a*n/n
$ ruby​​ a.rb 10 3
1
于 2010-06-10T03:38:07.427 に答える
4

子:52

main(a,b){scanf("%d%d",&a,&b);printf("%d",a-a/b*b);}
于 2010-06-10T03:45:59.380 に答える
4

Python: 25 文字

モジュラス演算子と同じように、負の数で動作します。カンマで区切られた 2 つの数値を取ります。

x,y=input()
print x-x/y*y
于 2010-06-10T03:27:19.333 に答える
3

Unefunge-98 141322 文字

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

Unefungeは、Funge-98の1次元インスタンスです: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 ()
于 2010-06-10T18:52:02.720 に答える
3

Clojure:30文字

#(if(>%2%1)%1(recur(-%1%2)%2)))
于 2010-06-10T04:02:51.203 に答える
2

スキーム: 38

(define(m a b)(- a(*(quotient a b)b)))
于 2010-06-10T03:54:57.177 に答える
2

ルビー:36文字

a,b=gets.split.map(&:to_i);p a-a/b*b
于 2010-06-10T03:19:15.030 に答える
2

JavaScript、11 文字

a-b*(0|a/b)

入力整数に変数aとが含まれていると仮定しbます。

a = 2;
b = 2;
alert(a-b*(0|a/b)); // => 0
于 2010-06-11T14:00:30.927 に答える
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));}
于 2010-06-18T03:23:34.457 に答える
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
于 2010-06-10T08:49:14.230 に答える
1

バッシュ、21 文字

echo $(($1-$1/$2*$2))
于 2010-06-16T22:36:52.033 に答える
1

PHP、49 文字

script.php?a=27&b=7の形式でクエリ文字列を入力し、短いタグがオンになっていると仮定します。

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

(一重引用符を取り除くことで 4 分の 1 に短縮できますが、通知がスローされます。)

vileregister_globalsをオンにすると、25 文字まで下げることができます。

<?echo $a-(int)($a/$b)*b;
于 2010-06-10T03:47:53.213 に答える
1

ジャバ。楽しみのためだけに

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);
    }
}
于 2010-06-10T03:20:05.373 に答える
0

DC:7文字(多分5;)

??37axp

次のように使用されます。

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

[そして、上記の他のいくつかの例を参照すると、入力をコードに挿入できる場合、5文字にすることができます。

37axp

のように:

dc -e "17 3 37axp"

言及する価値があると思っただけです]

于 2010-07-12T13:26:53.790 に答える
0

Perl25文字

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

利用方法:

echo 15 6 | perl modulo.pl
3
于 2010-06-21T15:34:42.783 に答える
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
)
于 2010-06-17T12:20:19.723 に答える
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);}}
于 2010-06-16T23:16:42.890 に答える
0

38文字のルビーで
p (a=gets.to_i)-((b=gets.to_i)*(a/b))
勝者ではない:(

于 2010-06-30T13:51:20.167 に答える
0

Java: 127 文字

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

入力が入力された後、出力が出力された後。

于 2010-06-11T18:51:48.433 に答える
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)))))
于 2010-06-12T13:01:50.937 に答える
0

DC: 8文字

odO/O*-p

$ echo '17 3 odO/O*-p' | dc
2
于 2010-06-16T22:41:08.123 に答える
0

Haskell、30 文字

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

これは私の最初のコード ゴルフです。コードについて自由にコメントし、改善点を投稿してください。;-)

勝てないことはわかっていますが、リストを使用してソリューションを共有したかっただけです。

于 2010-06-21T16:35:06.517 に答える
-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
于 2010-06-10T07:45:02.013 に答える