| Bytes | Lang | Time | Link |
|---|---|---|---|
| 115 | Bespoke | 250823T070612Z | Josiah W |
| nan | 250621T000310Z | RARE Kpo | |
| 017 | Swift 6 | 250621T135315Z | macOSist |
| 006 | BrainChild ASM | 241111T224938Z | ATaco |
| 020 | AWK | 241106T202527Z | xrs |
| 057 | Regex ECMAScript / Python | 210405T220557Z | Deadcode |
| 004 | Uiua | 231016T004919Z | chunes |
| 003 | Thunno 2 | 230728T014600Z | The Thon |
| 009 | Trilangle 1.3 | 230727T190606Z | Bbrk24 |
| 078 | TypeScript's Type System | 230727T024010Z | noodle p |
| 015 | Arturo | 230727T031821Z | chunes |
| 035 | Regex Perl / PCRE | 210406T022948Z | Deadcode |
| 060 | Scratch | 221205T053352Z | Rhaixer |
| 014 | ARBLE | 230323T214117Z | ATaco |
| 049 | ReRegex | 170327T220453Z | ATaco |
| 004 | Thunno DK | 230322T201242Z | The Thon |
| 007 | Japt | 230322T115002Z | Shaggy |
| 010 | Juby | 221204T232307Z | Jordan |
| 005 | MATL | 170327T135834Z | Suever |
| 006 | APL | 220711T031034Z | Vadim Tu |
| 028 | Desmos | 220701T210549Z | Aiden Ch |
| 020 | Haskell | 220711T045916Z | Monad |
| nan | 220711T022220Z | bigyihsu | |
| nan | Piet + asciipiet | 220701T201918Z | naffetS |
| 041 | Google Sheets | 220212T173619Z | Deera Wi |
| 020 | Factor | 211130T001403Z | chunes |
| 054 | Quipu | 211129T225904Z | DLosc |
| 019 | Grok | 210412T165510Z | Aaroneou |
| 003 | Vyxal | 210406T025714Z | lyxal |
| 004 | MathGolf | 200121T115827Z | Kevin Cr |
| 068 | Whitespace | 200121T114242Z | Kevin Cr |
| 005 | x8616 machine code | 191211T212253Z | 640KB |
| 003 | W r | 200120T142128Z | user8505 |
| 011 | 33 | 190915T090447Z | TheOnlyM |
| 1210 | Keg | 190915T080745Z | user8505 |
| 077 | Whispers v2 | 180412T120829Z | caird co |
| 009 | Implicit | 170910T035352Z | MD XF |
| 026 | Excel 2013 | 170327T135404Z | Luke |
| 019 | Triangular | 170616T181326Z | MD XF |
| 010 | Alice | 170411T200533Z | Martin E |
| 1189 | Taxi | 170411T205342Z | Engineer |
| 118 | NO! | 170402T202938Z | caird co |
| 108 | Funciton | 170327T141116Z | Martin E |
| 109 | SWI Prolog | 170331T104131Z | Jan Droz |
| 152 | Sinclair ZX80 16bit Integer BASIC 4K ROM | 170328T090036Z | Shaun Be |
| 008 | Pip | 170327T210811Z | steenber |
| 054 | BrainFlak | 170329T034714Z | 0 |
| 018 | TIBasic TI84 Plus CE | 170331T023630Z | pizzapan |
| 004 | Forth | 170330T183219Z | 2xsaiko |
| 035 | AHK | 170330T125445Z | Engineer |
| 031 | Mathematica | 170327T172754Z | Greg Mar |
| 283 | ArnoldC | 170328T135548Z | Tom291 |
| 025 | Gema | 170328T135238Z | manatwor |
| 025 | jq | 170328T134811Z | manatwor |
| 045 | Fortran 95 | 170328T133446Z | Steadybo |
| 020 | REXX | 170328T121653Z | idrougge |
| 021 | Haskell | 170327T154950Z | Laikoni |
| 005 | I | 170328T120613Z | Adá |
| 005 | APL Dyalog | 170327T152102Z | Adá |
| 007 | Pyth | 170328T102123Z | Erik the |
| 064 | BitCycle | 170328T073902Z | DLosc |
| 041 | brainfuck | 170327T221837Z | Dennis |
| 023 | QBasic 4.5 | 170327T211621Z | steenber |
| 014 | Retina | 170327T223455Z | Leo |
| 009 | J | 170327T215130Z | kaoD |
| 012 | dc | 170327T220530Z | Brian Mc |
| 027 | Ruby | 170327T194759Z | Redouane |
| 012 | Cubix | 170327T191406Z | MickyT |
| 021 | C | 170327T213119Z | Bijan |
| 012 | QBIC | 170327T210404Z | steenber |
| 040 | Lua | 170327T142255Z | Jör |
| 102 | OIL | 170327T125126Z | L3viatha |
| 036 | sed | 170327T192012Z | DLosc |
| nan | ><> | 170327T144041Z | Luke |
| 015 | Ouroboros | 170327T185250Z | DLosc |
| 003 | Pyke | 170327T182944Z | Blue |
| 031 | Cardinal | 170327T130803Z | fəˈnɛtɪk |
| 047 | brainfuck | 170327T164204Z | Leo |
| 014 | Jellyfish | 170327T161031Z | Martin E |
| 011 | Microscript | 170327T160732Z | SuperJed |
| 110 | BrainFlak | 170327T142626Z | Riley |
| 032 | C | 170327T155300Z | Abel Tom |
| 037 | Batch | 170327T154746Z | Neil |
| 106 | ForceLang | 170327T154647Z | SuperJed |
| 018 | Math++ | 170327T154101Z | SuperJed |
| 011 | Gol><> | 170327T145912Z | Erik the |
| 006 | GolfScript | 170327T132439Z | Erik the |
| 007 | CJam | 170327T131846Z | Erik the |
| 031 | PowerShell | 170327T140458Z | AdmBorkB |
| 010 | MATL | 170327T141340Z | Luis Men |
| 017 | JavaScript ES6 | 170327T124049Z | fəˈnɛtɪk |
| 024 | Elixir | 170327T135528Z | adrianmp |
| 025 | Forth | 170327T135455Z | mbomb007 |
| 035 | PHP | 170327T135311Z | Jör |
| 005 | 05AB1E | 170327T131339Z | Erik the |
| 013 | Wonder | 170327T132838Z | Mama Fun |
| 018 | Java 8 | 170327T131326Z | Socratic |
| 018 | Mathematica | 170327T125057Z | Martin E |
| 006 | Brachylog | 170327T130521Z | Fatalize |
| 003 | Jelly | 170327T130442Z | Erik the |
| 011 | Labyrinth | 170327T125927Z | Martin E |
| 020 | Python 2 | 170327T124821Z | Rod |
Bespoke, 115 bytes
using A at head,using B at tail
code for it can evaluate answer
having a div of/mod of integers
evaluating answer/s
STACKTOP MODULO gets the remainder of division, and STACKTOP QUOTIENTOF gets the quotient.
awk
Because the remainder is pre-subtracted-out from the dividend, the actual division is always exact by design, thus guaranteeing integer quotients (given integer inputs and non-zero divisor) even though awk lacks a specific operator, like python's a // b, for integer division.
echo '5 7\n5 1\n18 4\n255 25' |
awk '
function ___(_, __) {
return (_ - (_ %= __)) / __ "," _
}
$3 = ___($1, $2)'
5 7 0,5
5 1 5,0
18 4 4,2
255 25 10,5
As a bonus, the core expression is sign-agnostic. Some think of awk as having "no types". I think of it as awk simultaneously being every type, which makes polymorphism truly effortless.
Swift 6, 17 bytes
{(0+$0/$1,$0%$1)}
One of the less interesting answers here, posting it for completeness.
BrainChild ASM, 6 bytes
asm function divmod(int,int)->int,int{
apopb
apopa
divab
apusha
apushb
ret
}
Hex-dump of bytecode
0 1 2 3 4 5 6 7 8 9 A B C D E F
00000000: 35 34 23 2E 2F 14 | 54#./.
I/O on the stack which is the standard for BrainChild ASM functions. BrainChild's div instructions leave the remainder in the other register, conveniently.
BrainChild, 28 bytes
(int a,int b)->int,int=>a/%b
DivMod operator ftw.
AWK, 20 bytes
$0=int($1/$2)FS$1%$2
$0= # set default output
int($1/$2) # truncate decimal
FS # default field separator
$1%$2 # mod
Regex (ECMAScript / Python), 57 bytes
(x(x*)),(x*?)(?=\1*$)(x?(x*))(?=\4*$)((?=\2+$)\2\5*$|$\4)
Try it online! - ECMAScript
Try it online! - Python
Takes its arguments in unary, as two strings of x characters whose lengths represent the numbers. The divisor comes first, followed by a , delimiter, followed by the dividend. The quotient and remainder are returned in the capture groups \4 and \3, respectively.
I developed the basic form of this on 2014-04-03 while working on my abundant numbers regex. It had been a month earlier that teukon and I had independently come up with the multiplication algorithm described here, but up until this point we hadn't written or golfed any regex to find the unknown quotient of a known dividend and divisor. And it wasn't until dividing by \$\sqrt 2\$ that I adapted it to handle a dividend of zero correctly.
It is used, in its various forms (shown above or below), by these other regexes:
- Abundant numbers
- Fibonacci numbers - the version that returns the index
- OEIS A033286 (\$np_n)\$
- Factorial numbers
- Proth numbers
- Consecutive-prime/constant-exponent numbers
- Is the number binary-heavy?
- Euler's totient function by Grimmy
- Shift right by half a bit
- Decompose a number!
- Decide symmetry of fractions
Commented and indented:
(x(x*)), # \1 = divisor; \2 = \1-1; tail = dividend
(x*?)(?=\1*$) # \3 = remainder of division; tail -= \3
(x?(x*)) # \4 = conjectured quotient - find the largest one that matches the
# following assertions; \5 = \4-1, or 0 if \4==0; tail -= \4
(?=\4*$) # assert tail is divisible by quotient
(
(?=\2+$) # assert tail is positive and divisible by divisor-1
\2\5*$ # assert tail-(divisor-1) is divisible by quotient-1
|
$\4 # if dividend == 0, assert that quotient == dividend
)
To show what's going on, here is a Python function that does division using the regex's algorithm:
def modulo_is_zero(n, modulus):
return n==0 if modulus==0 else n>=0 and n % modulus == 0
def divide(dividend, divisor):
if divisor==0:
return
remainder = dividend % divisor
dividend -= remainder
quotient = dividend
if dividend != 0:
while 1:
if modulo_is_zero(dividend - quotient, quotient) and \
modulo_is_zero(dividend - quotient, divisor-1) and \
modulo_is_zero(dividend - quotient - (divisor-1), quotient-1):
break
quotient -= 1
if quotient == 0:
return
return [quotient, remainder]
Notice that in regex, \$0 \equiv 0 \pmod 0\$. This is very convenient, as it allows a quotient of \$1\$ to be returned with no special case. The only special case we actually need to handle is when the dividend is zero.
First, to demonstrate that the correct answer satisfies the assertions used – assume the remainder has already been subtracted away, and we are dividing \$B=C/A\$:
\$\begin{aligned} C &= AB \\ C-B &= (A-1)B \\ C-B-(A-1) &= (A-1)(B-1) \end{aligned}\$
Thus,
\$\begin{aligned} C &\equiv 0 \pmod A \\ C &\equiv 0 \pmod B \\ C-B &\equiv 0 \pmod {A-1} \\ C-B-(A-1) &\equiv 0 \pmod {B-1} \end{aligned}\$
The last two can be simplified to:
\$\begin{aligned} C &\equiv B \pmod {A-1} \\ C &\equiv A \pmod {B-1} \end{aligned}\$
At this point it becomes apparent why neither of these two alone would be enough. If \$A<B\$, it looks like the first one could yield false positives, and if \$B<A\$, it looks like the second one could. It turns out that only one of them is needed if we're guaranteed the input meets certain constraints, but until recently I simply accepted this intuitively and from testing the algorithm up to large numbers.
Unlike the multiplication algorithm, this division algorithm can't simply be proved correct from the Chinese remainder theorem, because \$C\$ is now constant while \$B\$, which defines one of the moduli, is the unknown. But thanks to H.PWiz, we finally have a rigorous proof for why the generalized form of division always works, and rigorously defined thresholds for when the division works in its two shortened forms.
Now let's look at ways to shorten the regex. First, if we assume \$C\ge A\$, it becomes 50 bytes:
(x(x*)),(x*?)(?=\1*$)(x(x*))(?=\4*$)(?=\2+$)\2\5*$
Try it online! - ECMAScript
Try it online! - Python
Try it online! - Python equivalent
If we know that all divisors will be in the required range, the division regex can be shortened further.
With \$C \equiv A \pmod {B-1}\$ and \$C \equiv 0 \pmod B\$, we need to find the largest matching quotient.
With \$C \equiv B \pmod {A-1}\$, we need to find the smallest matching quotient.
Coming in at 42 bytes, here is the case of using only \$C \equiv A \pmod {B-1}\$ and \$C \equiv 0 \pmod B\$:
(x(x*)),(x*?)(?=\1*$)(x(x*))(?=\4*$)\2\5*$
Try it online! - ECMAScript
This can be shortened further, thanks to a trick found by Grimmy (and used in this post). I've used it to shorten factorial, Proth, \$np_n\$, and consecutive-prime/constant-exponent regexes. As a standalone division regex, it comes in at 39 bytes:
(x+),(x*?)(?=\1*$)((x*)(?=\1\4*$)x)\3*$
Try it online! - ECMAScript
Try it online! - Python
Try it online! - Python non-regex equivalent
(x+), # \1 = divisor
(x*?)(?=\1*$) # \2 = remainder of division; tail -= \2
( # \3 = conjectured quotient - find the largest one that matches
(x*) # \4 = \3-1; tail -= \4
(?=\1\4*$) # assert tail-(quotient-1)-divisor is divisible by quotient-1
x # tail -= 1
)
\3*$ # assert both tail and dividend are divisible by quotient
The above algorithm is guaranteed to return the correct quotient if at least one of the following constraints is met (along with \$C \equiv 0 \pmod A\$):
- \$A^2+2A < 4C\$ or equivalently \$A+2 < 4B\$
- \$A=C\$ or equivalently \$B=1\$
- This works because the regex subtracts \$C-(B-1)-A\$ in order to assert that it is \$\equiv 0 \pmod {B-1}\$, and that subtraction will always result in a non-match (as it can't have a negative result) if \$A=C\$, unless \$B=1\$.
- \$A\$ is a prime power
- One of the cases in which this must be true, is when \$C\$ is semi-prime and neither of the two other conditions are met. It also must be true if \$C\$ is a prime power.
The proof of the first constraint follows. We start from the assertions made by the regex:
\$\begin{aligned} \qquad C &\equiv 0 \pmod B \\ C &\equiv A \pmod {B-1} \end{aligned}\$
Suppose the algorithm finds a \$B'\$ satisfying these moduli, with \$C=A'B'\$. Since the search for \$B\$ is done from largest to smallest, the only way for it to first find a \$B'\ne B\$ is with \$B<B'\$. Then:
\$\begin{aligned} \qquad C &\equiv 0 \pmod {B'} \\ C &\equiv A \pmod {B'-1} \\ A'B' &\equiv A \pmod {B'-1} \\ B' &\equiv 1 \pmod {B'-1} \end{aligned}\$
So, by modular division of \$A'B'/B'\$,
\$\qquad A' \equiv A \pmod {B'-1}\$
Due to \$AB=A'B'\$ and \$B<B'\$,
\$\begin{aligned} \qquad A &> A' \\ A &\ge A'+B'-1 \end{aligned}\$
Due to the AM-GM inequality, we have:
\$\begin{aligned} A'+B' &\ge 2\sqrt C \\ A'+B'-1 &\ge 2\sqrt C-1 \\ A &\ge 2\sqrt C-1 \\ {(A+1)}^2 &\ge {(2\sqrt C)}^2 \\ A^2+2A+1 &\ge 4C \end{aligned}\$
So for a \$B'\$ to be found, \$A^2+2A+1 \ge 4C\$ must be true. Therefore, if \$A^2+2A+1 < 4C\$, no such \$B'\$ will be found. But \$A^2+2A+1 = 4AB\$ has no solutions:
\$\begin{aligned} A^2+2A+1 &\stackrel?= 4AB \\ A &> 0 \\ A+2+{1\over A} &\ne 4B \end{aligned}\$
So we can simplify the inequality that guarantees no \$B'\$ will be found:
\$\begin{aligned} A^2+2A+1 &\le 4C \\ A^2+2A &< 4C \end{aligned}\$
And now the proof of the prime power constraint. Suppose that \$A\$ is a prime power and the algorithm has found a \$B'\$:
\$\begin{aligned} \qquad A&=p^n \\ A'B'&=C\\ B'&>B \\ A'&<A \\ A' &= p^{n-k},\ k>0 \end{aligned}\$
So \$B'\$ must have gained the prime power factor that \$A'\$ lost:
\$\begin{aligned} \qquad B' &= xp^k\\ B' &\equiv 0 \pmod p \\ A &\equiv 0 \pmod p \end{aligned}\$
So \$A\$ and \$B'-1\$ are coprime, and we can do modular division by \$A\$, since it is not \$\equiv 0 \pmod {B'-1}\$:
\$\begin{aligned} \qquad C &\equiv A \pmod {B'-1} \\ AB &= A\pmod {B'-1} \\ A &\equiv A \pmod {B'-1} \\ B &\equiv 1 \pmod {B'-1} \\ B &< B' \\ B &\le B'-1 \\ B &= 1 \end{aligned}\$
So for a \$B'\$ to be found when \$A=p^n\$, it must be the case that \$B=1\$, meaning \$A=C\$. But we already know that the algorithm works properly when \$A=C\$.
Coming in at 38 30 bytes, here is the case of using only \$C \equiv B \pmod {A-1}\$:
(x(x*)),(x*?)(?=\1*$)(x+?)\2+$
Try it online! - ECMAScript
Try it online! - Python
Try it online! - Python non-regex equivalent
(x(x*)), # \1 = divisor; \2 = \1-1; tail = dividend
(x*?)(?=\1*$) # \3 = remainder of division; tail -= \3
(x+?) # \4 = conjectured quotient - find the smallest one that matches
\2+$ # assert tail is positive and divisible by divisor-1
The above algorithm is guaranteed to return the correct quotient if at least one of the following constraints is met:
- \$A^2 > C \ge A\$ or equivalently \$A > B \ge 1\$
- \$A=1\$ or equivalently \$B=C\$
The proof of the first constraint follows. Starting from the assertion made by the regex:
\$\qquad C \equiv B \pmod {A-1}\$
Suppose the algorithm finds a \$B'\$ satisfying this modulus. Since the search for \$B\$ is done from smallest to largest, the only way for it to first find a \$B'\ne B\$ is with \$B>B'>0\$. Then:
\$\begin{aligned} \qquad C &\equiv B' \pmod {A-1} \\ AB &\equiv B' \pmod {A-1} \\ A &\equiv 1 \pmod {A-1} \end{aligned}\$
So, by modular division of \$AB/A\$,
\$\begin{aligned} B &\equiv B' \pmod {A-1} \\ B &> B' \\ B &\ge B' + A-1 \\ B-(A-1) &\ge B' > 0 \\ B-(A-1) &> 0 \\ B &> A-1 \\ B &\ge A \end{aligned}\$
So for a \$B'\$ to be found, \$B \ge A\$ must be true. Therefore, if \$B < A\$, no such \$B'\$ will be found.
This regex was actually discovered just for the sake of this post, to complete the symmetry. Then the math above proved it could be shortened from 38 to just 30 bytes by dropping the assertion of \$C \equiv 0 \pmod B\$, which was not referenced anywhere in the proof; I hadn't even tried shortening it that much beforehand.
At the time of posting it had never yet been used in a larger regex. Since then I found the perfect use for it in Shift right by half a bit, shortening that regex by 141 bytes.
So now let's prove that the generalized form of division works for all inputs. We have:
\$\begin{aligned} \qquad C &\equiv 0 \pmod {B} \\ C &\equiv B \pmod {A-1} \\ C &\equiv A \pmod {B-1} \end{aligned}\$
Suppose the algorithm finds a \$B'\$ satisfying these moduli, with \$C=A'B'\$. Since the search for \$B\$ is done from largest to smallest, the only way for it to first find a \$B'\ne B\$ is with \$0<B<B'\$. So now, doing the same steps we did for the two shortened forms of division:
\$\begin{aligned} C &\equiv 0 \pmod {B'} \\ C &\equiv A \pmod {B'-1} \\ A'B' &\equiv A \pmod {B'-1} \\ B' &\equiv 1 \pmod {B'-1} \\ A' &\equiv A \pmod {B'-1} \\ A' &< A \\ A'+B'-1 &\le A \end{aligned}\$ \$\begin{aligned} \ \\ C &\equiv B' \pmod {A-1} \\ AB &\equiv B' \pmod {A-1} \\ A &\equiv 1 \pmod {A-1} \\ B &\equiv B' \pmod {A-1} \\ B &< B' \\ B+A-1 &\le B' \end{aligned}\$
Putting it together,
\$\begin{aligned} B+A-1 &\le B' \\ B+(A'+B'-1)-1 &\le B' \\ B+A'+B'-2 &\le B' \\ B+A' &\le B'-B'+2 \\ B+A' &\le 2 \\ B &> 0 \\ A' &> 0 \\ B = A' &= 1 \\ B' &= C \\ A &= C \end{aligned}\$
So for a \$B'\$ to be found, \$B'=C\$ and \$A=C\$ must be true. But the regex tries to assert the modulus
\$C-B'-(A-1) \equiv 0 \pmod {B'-1}\$
But if \$B'=C\$ and \$A=C\$, this becomes
\$\begin{aligned} C-C-(C-1) \equiv 0 \pmod {B'-1} \\ 0-(C-1) \equiv 0 \pmod {B'-1} \end{aligned}\$
If \$C>1\$, the regex will fail to subtract \$C-1\$ from \$0\$ before it can even try to assert the modulus, thus the search for \$B\$ will continue with other values, and the correct one will be found.
If \$C=A=1\$, the answer \$B'=1\$ is correct, as \$B=1\$ in this case.
Therefore the regex will always give the correct answer for \$C>0\$, and since \$C=0\$ is handled as a special case, it will give the correct answer for all inputs.
Uiua, 4 bytes
⌊⊃÷◿
⌊⊃÷◿
⊃ # fork (in this case apply two functions to the same two arguments)
◿ # mod
÷ # divide
⌊ # floor
Thunno 2, 3 bytes
禌
ç: Apply two commands parallelly:¦: swapped integer divisionŒ: swapped modulo
Trilangle 1.3, 9 bytes
??!z,!:%@
Try it on the online interpreter!
TODO: Add colorized explanation
?? Read two numbers in
z Duplicate them both
: Compute the quotient
! Print the quotient followed by a newline
, Pop the quotient off the stack
% Compute the remainder
! Print the remainder (followed by a newline)
@ Terminate the program
The z instruction (DP2) makes this fairly straightforward. Without that, the answer is a bit more involved:
Trilangle 1.0, 13 bytes
??j2S,':%@2!!
?? Read two numbers in
2 Duplicate the one on top of the stack
' 2 Push the number 2...
j ...and use it to index into the stack, copying the bottom to the top
S Swap the top two values, so the stack is [a b a b] instead of [a b b a]
, : ! Compute, print, and pop the quotient
% ! Compute and print the remainder
@ Terminate the program
TypeScript's Type System, 78 bytes
//@ts-ignore
type M<A,B,T=[]>=A extends[...B,...infer I]?M<I,B,[...T,1]>:[T,A]
Try it at the TypeScript Playground!
This submission is a generic type taking in two numbers in unary and outputting a tuple of two unary numbers, the first being the division and the second the remainder.
Explanation:
//@ts-ignore // ignore any compiler errors in this type
type M<
A, // A is the numerator
B, // B is the denominator
T = [] // T is the # of times recursed (division result)
> =
A extends [...B, // if B fits in A (A >= B):
...infer I // set I to the difference (A - B)
] ? M< // recurse with:
I, // I as the numerator
B, // B as the denominator
[...T, 1] // T with 1 appended (i.e. increment)
>
: [T, A] // otherwise return [T, A]
This uses tail recursion to increase the maximum recursion depth from 50 to 999.
Regex (Perl / PCRE), 36 35 bytes
x(x*),((x(?=((?(4)\4)\1)))*)\4?(x*)
Takes its arguments in unary, as two strings of x characters whose lengths represent the numbers. The divisor comes first, followed by a , delimiter, followed by the dividend. The quotient and remainder are returned in the capture groups \2 and \5, respectively.
In contrast to the ECMAScript regex solution, this one doesn't have to do anything anywhere near as fancy or mathematically interesting. Just count the number of times \$divisor\$ fits into \$dividend\$ by splitting the divisor to keep two tandem running totals that are both subtracted from \$dividend\$, one that keeps subtracting \$divisor-1\$, and one that keeps subtracting \$1\$ and adding it to the total quotient. We must do a split like this, because regex refuses to repeat a zero-width group more than once (this, along with the limited space to work in, is exactly what prevents it from being Turing-complete).
I never wrote a division algorithm in any regex flavor besides ECMAScript before. So it's interesting to now know how they compare in golfed size.
x(x*), # \1 = divisor-1; tail = dividend
( # \2 = what will be the quotient
(
x # tail -= 1
(?=
( # \4 = running total
(?(4)\4) # recall the previous contents of \4, if any
\1 # \4 += divisor-1
)
)
)* # Loop the above as many times as possible (zero or more); if
# it loops zero times, \4 will be unset (we'll treat that as 0)
)
\4? # tail -= \4, or leave tail unchanged if \4 is unset
(x*) # \5 = remainder
Regex (Java), 41 40 38 bytes
x(x*),((x(?=(\4\1|(?!\3)\1)))*)\4?(x*)
This is a port of the Perl/PCRE regex to a flavor that has no conditionals. Emulating a conditional costs 5 3 bytes here. The quotient and remainder are returned in the capture groups \2 and \5, respectively.
x(x*), # \1 = divisor-1; tail = dividend
( # \2 = what will be the quotient
( # \3 = the following (after the first iteration has finished),
# which is always 1
x # tail -= 1
(?=
( # \4 = running total
\4 # recall the previous contents of \4 (only if it is set)
\1 # \4 += divisor-1
|
(?!\3) # Match this alternative only if this is the first iteration of
# the loop, meaning \4 is unset; \3 can never not match here if
# \3 is set (because \3==1) unless \1==0, in which case it
# doesn't matter if this alternative is taken instead of the
# above – in that case, the value of \4 isn't changed anyway.
\1 # \4 = divisor-1
)
)
)* # Loop the above as many times as possible (zero or more); if
# it loops zero times, \4 will be unset (we'll treat that as 0)
)
\4? # tail -= \4, or leave tail unchanged if \4 is unset
(x*) # \5 = remainder
Regex (Pythonregex / Ruby), 43 bytes
x(x*),((x(?=((?(5)\5)\1))(?=(\4)))*)\4?(x*)
Try it online! - Python import regex
Try it online! - Ruby
This is a port of the Perl/PCRE regex to flavors that have no support for nested backreferences. Python's built-in re module does not even support forward backreferences, so for Python this requires regex.
Emulating a nested backreference by copying the group back and forth costs 8 bytes here. The quotient and remainder are returned in the capture groups \2 and \6, respectively.
x(x*), # \1 = divisor-1; tail = dividend
( # \2 = what will be the quotient
(
x # tail -= 1
(?=
( # \4 = running total
(?(5)\5) # recall the previous contents of \4 (as copied into \5) if any
\1 # \4 += divisor-1
)
)
(?=(\4)) # \5 = \4, to make up for Python's lack of nested backreferences
)* # Loop the above as many times as possible (zero or more); if
# it loops zero times, \4 will be unset (we'll treat that as 0)
)
\4? # tail -= \4, or leave tail unchanged if \4 is unset
(x*) # \6 = remainder
Regex (.NET), 29 bytes
(x+),(?=(\1)*(x*))((?<-2>x)*)
This uses .NET's Balanced Groups feature. It returns the quotient and remainder in the lengths of \4 and \3, respectively.
(x+), # \1 = divisor; assert \1 > 0; tail = dividend
(?=
(\1)* # push \2 onto the stack for each time \1 fits into dividend
(x*) # \3 = remainder
)
((?<-2>x)*) # \4 = quotient: pop all \2 from stack, doing \4 += 1 for each
Regex 🐘 (.NET), 14 bytes
(x+),(\1)*(x*)
This uses .NET's Balanced Groups feature. It returns the quotient in the capture count of \2, and remainder in the length of \3.
Scratch, 60 bytes
define(x)(y
say(join(join([floor v]of((x)/(y)))[,])((x)mod(y
+12 bytes due to an error reported by xigoi
ARBLE, 14 bytes
a//b..","..a%b
6 bytes longer than I'd like, but I couldn't find a shorter way to deliminate the two as a//b,a%b simply returns the two functions.
ReRegex, 75 49 Bytes.
#import math
s(\d+),(\d+)e/$1\/$2,$1%$2/s#input
e
Explanation
This simply performs the following Regex Substitution
s(\d+),(\d+)e/$1/$2,$1%$2
And the input line is simply
s(?#input)e.
The s...e takes the input in the form of 123,123 and wraps it, so we know to execute a function on it. In particular, line 2, which changes 123,456 to 123/456,123%456.
Then, all of it is taken care of by the math library.
Thunno DK, 4 bytes
(Actually \$4\log_{256}(96)\approx\$ 3.29 bytes but the leaderboard doesn't take decimals)
|X$x
Explanation
|X # Integer division, store in X
$x # Modulus, push X
# Implicit output of the stack
Japt, 7 bytes
£rYguiz
£rYguiz :Implicit input of array U
£ :Map each element at index Y
r : Reduce U by
Yg : Index Y into
uiz : prepend "z" (floor division) to "u" (modulo)
J-uby, 10 bytes
-[+:/,+:%]
Explanation
The built-in way would be :divmod (7 bytes) but since that’s forbidden we have:
-[ +:/, +:% ]
-[ , ] # Apply each function to the input and return an array of the results
+:/ # Divide (`+` splats an array into separate arguments)
+:% # Modulo
MATL, 5 bytes
/k&G\
Try it out at MATL Online!
Explanation
% Implicitly grab the two inputs as numbers
/ % Divide them
k % Round down the result
&G % Grab the two inputs again
\ % Compute the remainder
APL, 6 bytes
{0⍵⊤⍺}
Definitely not the shortest possible solution, but the classic one, should be compatible with any APL implementation.
Haskell, 20 bytes
(<*>).(<*>)[div,mod]
Arguments are passed as singleton lists, for example: ((<*>).(<*>)[div,mod]) [10] [3] returns [3,1].
The <*> operator takes a list of function and a list of values, and applies each function to each value. This function puts div and mod in a list, and then passes two arguments to them using <*>.
Haskell also has the builtin divMod which does the same thing (it takes two integers and returns a tuple).
Go, 38 bytes
func(a,b int)(int,int){return a/b,a%b}
Anonymous function that takes 2 ints and returns 2 ints.
Piet + ascii-piet, 18 bytes (14×2=28 codels)
TABlIiIAQJICSBqKkk
Separates by \x01.
-22 bytes thanks to Aiden Chow
Google Sheets, 41 bytes
=concatenate(MOD(A1,A2)," ",QUOTIENT(A1,A2
A1 = divident and
A2 = diviser
Last parentheses are auto completed.
Factor, 20 bytes
Stack shuffling:
[ 2dup /i -rot mod ]
Explanation
! 24 9
2dup ! 24 9 24 9
/i ! 24 9 2
-rot ! 2 24 9
mod ! 2 6
Factor, 22 bytes
Data flow combinators:
[ [ /i ] [ mod ] 2bi ]
Factor, 25 bytes
Local variables:
[| a b | a b /i a b mod ]
Factor, 4 bytes
Built-in:
/mod
Quipu, 54 bytes
\/\/[]\n[]
1&/\1&
[] []
// %%
/\ /\
Explanation
Each pair of columns constitutes a "thread." Threads are executed one at a time, top to bottom, left to right. Each thread also stores a value (initially 0).
Each of threads 0 and 1 uses the \/ knot to read a number from stdin and stores that number as its value.
Thread 2 does the following:
[]: Get the value of thread N, where N is the previous value of this thread. Here, there is no previous value, so we get the value of thread 0.1&: Push a 1.[]: Get the value of thread N, where N is the 1 we just pushed.//: Integer-divide the last two values./\: Output the result.
Thread 3 sets its value to a string containing a newline (\n) and then outputs it (/\).
Thread 4 does the same thing as thread 2, but with modulo (%%) instead of division.
Grok, 19 bytes
:Yp:Y%zp/Yp1%-I,Wzq
This outputs remainder,division. Additionally, inputs must be passed through STDIN; it can't be piped from another command.
Explanation:
:Yp # Takes the first integer from STDIN and duplicates it.
:Y # Takes the second integer from STDIN and duplicates it to the register.
%z # Modulos the two numbers and outputs the remainder.
p # Moves the second number from the register to the Document (stack).
/ # Performs float division on the two numbers.
Yp1%- # Floor function shamelessly stolen from https://stackoverflow.com/a/5123037/10363591
I,W # Pushes , to the stack and outputs it.
zq # Outputs quotient and terminates.
Vyxal, 3 bytes
₍ḭ%
The header and footer are for formatting purposes. Otherwise takes arguments in reversed order.
Explained
₍ḭ%
₍ # parallel apply the next two commands and collect into a list:
ḭ% # integer divide and modulo
MathGolf, 4 bytes
‼/%]
Inputs in the order b a, output as a list containing two integers.
Explanation:
‼ # Apply the following two commands to the stack separately:
/ # Division (which will be integer division if the given arguments are integers)
% # Modulo
# (both builtins will use the implicit input-integers for their two required arguments)
] # Then wrap all values on the stack into a list
# (after which the entire stack joined together is output implicitly as result)
For an actual character-separated string, we could use one of these instead for 5 bytes: ‼/% \ (space separator); ‼/%n\ or ‼/%]n (newline separator); ‼/%⌂\ (* separator).
Whitespace, 68 bytes
[S S S N
_Push_0][S N
S _Dupe_0][T N
T T _Read_STDIN_as_integer][T T T _Retrieve_input1][S N
S _Dupe_input1][S N
S _Dupe_input1][T N
T T _Read_STDIN_as_integer][T T T _Retrieve_input2][T S T S _Integer_divide][T N
S T _Print_as_integer][S S S T S T S N
_Push_10_newline][T N
S S _Print_as_character][S S S N
_Push_0][T T T _Retrieve_input1][S N
S _Dupe_input1][T T T _Retrieve_input2][T S T T _Modulo][T N
S T _Print_as_integer]
Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.
Try it online (with raw spaces, tabs and new-lines only).
Prints with a newline delimiter (could alternatively be a tab for the same byte-count).
Explanation in pseudo-code:
Integer a = STDIN as integer
Integer b = STDIN as integer
Print a integer-divided by b
Print "\n"
Print a modulo-b
Example program flow (inputs 255 and 25):
Command Explanation Stack Heap STDIN STDOUT STDERR
SSSN Push 0 [0]
SNS Duplicate 0 [0,0]
TNTT Read STDIN as integer [0] [{0:255}] 255
TTT Retrieve from heap #0 [255] [{0:255}]
SNS Duplicate 255 [255,255] [{0:255}]
SNS Duplicate 255 [255,255,255] [{0:255}]
TNTT Read STDIN as integer [255,255] [{0:255},{255:25}] 25
TTT Retrieve from heap #255 [255,25] [{0:255},{255:25}]
TSTS Integer divide (255/25) [10] [{0:255},{255:25}]
TNST Print as integer [] [{0:255},{255:25}] 10
SSSTSTSN Push 10 [10] [{0:255},{255:25}]
TNSS Print as character [] [{0:255},{255:25}] \n
SSSN Push 0 [0] [{0:255},{255:25}]
TTT Retrieve from heap #0 [255] [{0:255},{255:25}]
SNS Duplicate 255 [255,255] [{0:255},{255:25}]
TTT Retrieve from heap #255 [255,25] [{0:255},{255:25}]
TSTT Modulo (255%25) [5] [{0:255},{255:25}]
TNST Print as integer [] [{0:255},{255:25}] 5
error
Program stops with an error because no exit is defined.
Since the inputs are guaranteed to be non-negative, I'm using the first input as heap-address to store the second input to save bytes.
x86-16 machine code, 5 bytes (non-competing?)
88 1E 0105 MOV BYTE PTR[AAM1+1], BL ; modify second byte of AAM opcode for divisor
AAM1:
D4 ? AAM ; ASCII Adjust AX After Multiply
Input numbers in AL and BL. Output division in AH, remainder in AL.
This "abuses" the x86 "ASCII adjust after multiply" instruction intended to facilitate multiplication of binary coded decimal values (BCD), to convert results to base-10 values. These instructions were deprecated in x64, however as an under-documented feature this behavior can be altered by using self-modifying code to perform arbitrary base conversion of variable input data.
Caveat:
The challenge does state Builtins that return both the result of the division and the remainder are forbidden. These operations are always done at the same time in x86 machine code so not clear if this would disqualify the platform. This answer, however, does not use the x86's DIV instruction. Question posed to OP. :)
W r, 3 bytes
/@m
Explanation
abab % Implicit ops
/ % Divide a by b. Stack: a b (a/b)
@ % Roll down to show 2 operands. Stack: (a/b) a b
m % Modulo the operands. Stack: (a/b) (a%b)
% Output the whole stack
```
33, 11 bytes
OcOcsdoilro
Explanation
OcOc | Harvest input from user
s | Store "a" for later use
doi | Print the integer division followed by a newline
l | Get "a" back
ro | Print the remainder of the division
Keg, 12 10 bytes
Other than the creator, I think only I am actively using it. Therefore it is rarely seen on this site; in addition it is esoteric.
Takes 2 inputs separated with newlines.
¿¿:^:"$/"%
Explanation
¿¿# Takes 2 integer inputs: e.g. stack [1, 2]
:# Duplicate the top item. stack [1, 2, 2]
^# Reverse the stack. stack [2, 2, 1]
:# Duplicate the stack. stack [2, 2, 1, 1]
"# Right shifts (put top to bottom) stack [1, 2, 2, 1]
$# Swap top two items stack [1, 2, 1, 2]
/# Divide top two stack [1, 2, 0.5]
"# Right shifts stack [0.5, 1, 2]
%# Modulos top two items stack [0.5, 1]
# Stack is implicitly outputted
Whispers v2, 77 bytes
> Input
> Input
>> 1÷2
>> ⌊3⌋
>> 1%2
>> Output 4
>> Output 5
>> Then 6 7
Implicit, 9 bytes
$$|/%;_@9
$$|/%;_@9
$$ read two integer inputs
| duplicate stack
/ division
% print
; pop
_ modulus
@9 print HTAB (delimiter)
Excel 2013, 31 30 26 bytes
=INT(A1/B1)&","&MOD(A1;B1)
Explanation
Input is in cell A1 and B1. This simply returns the return values of the FLOOR and MOD function, which are for flooring the division and for the remainder. These values are separated by a comma.
Triangular, 21 19 bÿtes
$\:A@$U.vS/p%_<%mp<
Prints the result of division, a newline, then the remainder. Formats into this triangle:
$
\ :
A @ $
U . v S
/ p % _ <
% m p < ÿ ÿ
ÿ is the no-op that is automaticallÿ inserted when there is no code to fill the smallest possible triangle.
Explanation:
I don't know whÿ Removed it and managed to save two bÿtes. Still don't know whÿ it was there in the first place. ಠ_ಠ\ is the first character...
Directionals:
.
\ .
. . .
. . v .
/ . . . <
. . . <
This is how the interpreter sees the code, without directionals:
$:$S_%pUA@pm%
$:reads integer input to the stack and duplicates it. Stack containsinput1 input1.$Sreads another input to the stack, then stashes it in memorÿ. Stack containsinput1 input1 input2, and memorÿ containsinput2._divides the top two stack values. Now the stack containsinput1 input1/input2.%prints the top of stack as an integer.ppops the top of stack. Now the stack containsinput1.Upulls memorÿ onto the stack. Now the stack containsinput1 input2.Apushes 10 to the stack. Stack containsinput1 input2 10.@prints it as ASCII (newline).ppops it - stack containsinput1 input2.mperforms modulus on the top two stack values. Stack now containsinput1%input2.%prints the top of stack as an integer.- the IP then runs off the plaÿing field, and the program terminates.
Alice, 12 10 bytes
\%.\
O:io
Explanation
Alice does have a divmod built-in, which would allow a solution in at most 7 bytes:
</
iMOP
(The P could be any character whatsoever, so I thought I'd put the image of Apple-branded cleaning products in your head. You're welcome.)
But without that built-in, things certainly get a bit more interesting.
Since Alice also has separate built-ins for division and modulo, the program is entirely linear, but the instruction pointer takes a fairly tricky path through the code. Here is the breakdown of the program flow:
\ Reflect to NE. Switch to Ordinal
Reflect off boundary --> SE.
i Read all input as a string.
Reflect off boundary --> NE.
. Duplicate the input string.
Reflect off boundary --> SE.
Reflect off corner --> NW.
. Duplicate the input string. (Irrelevant)
Reflect off boundary --> SW.
i Try to read more input, but that just pushes "".
Reflect off boundary --> NW.
\ Reflect to S. Switch to Cardinal.
: Implicitly discard the empty string and convert a copy of the input
to the two integers it contains and compute the result of their integer division.
IP wraps back to the first line.
\ Reflect to NW. Switch to Ordinal.
Reflect off boundary --> SW.
O Implicitly convert the division result to a string and print it with a
trailing linefeed.
Reflect off corner --> NE.
\ Reflect to E. Switch to Cardinal.
% Implicitly convert a copy of the input to the two integers it contains
and compute the result of their modulo.
. Duplicate the modulo result. (Irrelevant)
\ Reflect to NE. Switch to Ordinal.
Reflect off corner --> SW.
o Implicitly convert the modulo reuslt to a string and print it without a
trailing linefeed.
At this point we're basically done. The IP does a few more rounds through the code and pushes and prints a few more empty strings, but none of that affects the output. Eventually, the code will attempt a division by zero which terminates the program. The instructions executed by Alice after the last meaningful o are:
%::%o\\i..i\:
The exact movement of the IP through the grid and what exactly these commands do to the stack are left as an exercise to the reader...
Taxi, 1189 bytes
"," is waiting at Writer's Depot.Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to The Babelfishery.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Cyclone.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 1 l 2 r.Pickup a passenger going to What's The Difference.Pickup a passenger going to Divide and Conquer.Pickup a passenger going to Divide and Conquer.Go to Divide and Conquer:n 2 r 2 r 1 r.Pickup a passenger going to Trunkers.Go to Trunkers:e 1 r 3 r 1 l.Pickup a passenger going to Cyclone.Go to Cyclone:w 2 r.Pickup a passenger going to Multiplication Station.Pickup a passenger going to Multiplication Station.Go to Multiplication Station:s 1 l 2 r 4 l.Pickup a passenger going to What's The Difference.Go to Cyclone:s 1 r 2 l 2 r.Pickup a passenger going to The Babelfishery.Go to What's The Difference:n 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:e 3 r.Pickup a passenger going to Post Office.Go to Writer's Depot:n 1 l 1 l 2 l.Pickup a passenger going to Post Office.Go to The Babelfishery:n 1 r 2 r 1 r.Pickup a passenger going to Post Office.Go to Post Office:n 1 l 1 r.
With line breaks:
"," is waiting at Writer's Depot.
Go to Post Office:w 1 l 1 r 1 l.
Pickup a passenger going to The Babelfishery.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery:s 1 l 1 r.
Pickup a passenger going to Cyclone.
Pickup a passenger going to Cyclone.
Go to Cyclone:n 1 l 1 l 2 r.
Pickup a passenger going to What's The Difference.
Pickup a passenger going to Divide and Conquer.
Pickup a passenger going to Divide and Conquer.
Go to Divide and Conquer:n 2 r 2 r 1 r.
Pickup a passenger going to Trunkers.
Go to Trunkers:e 1 r 3 r 1 l.
Pickup a passenger going to Cyclone.
Go to Cyclone:w 2 r.
Pickup a passenger going to Multiplication Station.
Pickup a passenger going to Multiplication Station.
Go to Multiplication Station:s 1 l 2 r 4 l.
Pickup a passenger going to What's The Difference.
Go to Cyclone:s 1 r 2 l 2 r.
Pickup a passenger going to The Babelfishery.
Go to What's The Difference:n 1 l.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery:e 3 r.
Pickup a passenger going to Post Office.
Go to Writer's Depot:n 1 l 1 l 2 l.
Pickup a passenger going to Post Office.
Go to The Babelfishery:n 1 r 2 r 1 r.
Pickup a passenger going to Post Office.
Go to Post Office:n 1 l 1 r.
NO!, 118 bytes
It is too insane to do this challenge with NO! which is why it's non-competing (not really, the language is too young to compete in the bloodthirsty arena known as PPCG)
NOOOOOOOOOOOO?NOOOOOOOOOOO
NOOOOOOOOOOOO?NOOOOOOOOOOO
NOOOOO?yes!yess
NOOOOOOOOOOOOOOOOO?yes!yess
NOOOOOOOO?nooo!noooo
Please say you don't want an explanation (one added anyway)
NOOOOOOOOOOOO? Create an integer from
NOOOOOOOOOOO STDIN
NOOOOOOOOOOOO? Create an integer from
NOOOOOOOOOOO STDIN
NOOOOO? Divide by
yes! line 1 result
yess line 2 result
NOOOOOOOOOOOOOOOOO? Modulo by
yes! line 1 result
yess line 2 result
NOOOOOOOO? Output and
nooo! line 3 result
noooo line 4 result
A yes is used to denote a line number (number determined by number of ss) but the output command takes either numbers or line numbers as arguments and noo!nooo is shorter than yess!yesss
Funciton, 224 108 bytes
Byte count assumes UTF-16 encoding with BOM.
┌──┬───┐
┌┴╖╓┴╖ ┌┴╖
│%╟║f╟┐│÷╟┘
╘╤╝╙─╜│╘╤╝
└────┴─┘
The above defines a function f, which takes two integers and returns both their division and their product (functions in Funciton can have multiple outputs as long as the sum of inputs and outputs doesn't exceed 4).
Using two input values for multiple purposes is actually quite trivial: you simply split off the connector with a T-junction at the value will be duplicated along both branches, which we can then feed separately to the built-ins for division and modulo.
It actually took me twice as long to figure out how to display the result to the user than just to implement the solution.
Also, Funciton has a built-in divmod, ÷%, and amusingly the built-ins ÷ and % that my solution uses are implemented in terms of ÷%. However, my function f above isn't quite identical to ÷%: I had to swap the order of the inputs and although it seems like it should be easy to change that, so far I haven't been able to do so without increasing the byte count.
SWI Prolog, 109 bytes
p(A):-print(A).
d(F,S,0,F):-S>F.
d(F,S,D,R):-G is F-S,d(G,S,E,R),D is E+1.
d(F,S):-d(F,S,D,R),p(D),p(-),p(R).
Output:
?- d(255,25).
10-5
true .
?- d(5,7).
0-5
true .
Description:
Simple recursive algorithm without builtin division or modulo. It simply counts "how many times fits the Second number into the First one?" and reports the result (unified to D) with the remainder (R).
//edit: removed unnecessary spaces
Sinclair ZX80 16-bit Integer BASIC (4K ROM), ~152 BASIC bytes used (listing)
1 LET R=0
2 PRINT "ENTER A NUMBER THEN DIVISOR"
3 INPUT Z
4 INPUT D
5 PRINT Z;"/";D;"=";
6 GO SUB 9
7 PRINT R;" REMAINDER ";Z
8 STOP
9 FOR I=1 TO 0
10 LET Z=Z-D
11 LET R=R+1
12 LET I=(Z>D)+(Z=D)
13 NEXT I
14 RETURN
Some notes:
Because the ZX80 (with the old ROM) can only handle 16-bit signed integer numbers, your range is -32768 to +32767 for your inputs. There is no native modulo function, nor does there seem to be a >= (if there is then I can't find it) - hence why this had to be split in line 12.
I haven't handled the division by zero in the program, but I guess that it entering 0 as your divisor will keep the sub-routine from line 9 in an infinite loop (as it should), except for the 16-bit integer range, so Z/0 should be Z r ∞.
The byte count is only an approximation for now.
Pip, 8 bytes
Pa//ba%b
Explanation:
The input is read automatically into the vars a and b
a%b calculate a%b. Since this is the last thing we do, this is printed implicitly.
a//b We also want to show a // b (double slashes is integer div).
P So we need an explicit PRINT command.
Brain-Flak, 56 54 bytes
({}<>)<>([()]{()<(({})){({}[()])<>}{}>}<><([{}()]{})>)
-2 bytes thanks to Wheat Wizard
Explanation
The current best known integer division and modulo in Brain-Flak are very similar (in fact the currently used integer division is just a modification I made on feersum's modulo).
Comparison of modulo and integer division:Modulo: ({}(<>))<> { (({})){({}[()])<>}{} }{}<> ([{}()]{})
Division: ({}(<>))<>([()]{()<(({})){({}[()])<>}{}>}{}<>< {} {} >)
Conveniently, the integer division program uses only the third stack for storing data while the modulo program uses only the normal two stacks for storing data. Thus by simply running them both at the same time they do not collide at each other.
Combination of modulo and integer division:Modulo: ({}(<>))<> { (({})){({}[()])<>}{} }{}<> ([{}()]{})
Division: ({}(<>))<>([()]{()<(({})){({}[()])<>}{}>}{}<>< {} {} >)
Combined: ({}(<>))<>([()]{()<(({})){({}[()])<>}{}>}{}<><([{}()]{})>)
Finally, both the integer division and modulo programs used in this combination were designed to be stack clean (not leave garbage on the stacks/not depend on the (non)existence of values on the stacks other than their input) but that is not necessary for this problem. Thus we can save two bytes by not bothering to pop the zero at the end of the main loop and another two bytes by not pushing zero at the start, instead relying on the zero padding on the bottom of the stacks.
This gives us the final program:({}<>)<>([()]{()<(({})){({}[()])<>}{}>}<><([{}()]{})>)
For the explanation for the integer division program see feersum's answer
Integer Division Explanation Coming Soon...
TI-Basic (TI-84 Plus CE): 18 bytes
Prompt A
Prompt B
{int(A/B),remainder(A,B
Prompt, A, B, newline, {, int(, /, ,, and ) are all one-byte tokens, but remainder( is a two-byte token.
Prompt prompts you for the numbers.
int(A/B) computes the floored division of A and B
remainder(A,B computes remainder when A is divided by B
{ causes the values of int(A/B) and remainder(A,B) to be stored to a list. This list is implicitly returned, as it is the last evaluated value in the program.
The returned list is printed as {divison remainder}, with a space between the numbers.
Note: TI-Basic does not require closing parentheses or brackets in most cases; one exception being here with int(A/B): the ) is needed so as not to pass the value after the comma as a second argument to int( (which would raise an Error: Syntax).
Forth, 4 bytes
/MOD
Top of stack will be the quotient, then the remainder.
AHK, 35 bytes
a=%1%
b=%2%
Send,% a//b ","Mod(a,b)
AutoHotkey assigns numbers 1-n as variable names for the incoming parameters. It causes some problems when you try to use those in functions because it thinks you mean the literal number 1 instead of the variable named 1. The best workaround I can find is to assign them to different variables.
Mathematica, 32 31 bytes
Thanks to Martin Ender for calming the code down to the tune of 1 byte!
0@#2//.a_@b_/;b>=#:>(a+1)[b-#]&
Just to mess with the language. Pure function taking the two positive integer arguments in the opposite (counterintuitive) order, and returning the quotient q and the remainder r in the same style, q[r], as in Martin Ender's Mathematica answer. While that answer is shorter, this one is ... more contrary? It implements repeated subtraction on expressions of the form a[b].
ArnoldC, 286 283 bytes
HEY CHRISTMAS TREE c
YOU SET US UP 0
HEY CHRISTMAS TREE d
YOU SET US UP 0
GET TO THE CHOPPER c
HERE IS MY INVITATION a
HE HAD TO SPLIT b
ENOUGH TALK
GET TO THE CHOPPER d
HERE IS MY INVITATION a
I LET HIM GO b
ENOUGH TALK
TALK TO THE HAND c
TALK TO THE HAND d
YOU HAVE BEEN TERMINATED
How It Works
HEY CHRISTMAS TREE c //DECLARE VARIABLE c = 0
YOU SET US UP 0
HEY CHRISTMAS TREE d //DECLARE VARIABLE d = 0
YOU SET US UP 0
GET TO THE CHOPPER c /*
HERE IS MY INVITATION a SET c = a/b
HE HAD TO SPLIT b
ENOUGH TALK */
GET TO THE CHOPPER d /*
HERE IS MY INVITATION a SET d = a mod b
I LET HIM GO b
ENOUGH TALK */
TALK TO THE HAND c // PRINT c
TALK TO THE HAND d // PRINT d
YOU HAVE BEEN TERMINATED //END
Output Format
a/b
a mod b
Gema, 25 characters
* *=@div{*;*} @mod{$1;$2}
Sample run:
bash-4.3$ gema '* *=@div{*;*} @mod{$1;$2}' <<< '255 25'
10 5
jq, 25 characters
def f(a;b):a/b|floor,a%b;
Sample run:
bash-4.3$ jq -n 'def f(a;b):a/b|floor,a%b;f(255;25)'
10
5
Fortran 95, 45 bytes
function f(i,j)
write(*,*)i/j,modulo(i,j)
end
REXX, 20 bytes
arg a b
say a%b a//b
Haskell, 21 bytes
a#b=(div a b,mod a b)
Try it online! Example usage: 13#2 returns (6,1). Yes, this is pretty boring, however slightly more interesting than the divMod build-in which works the same.
While we are at it, there is also quot, rem and quotRem which behave the same on natural numbers as div, mod and divMod. However, for negative inputs the result of mod has the same sign as the divisor, while the result of rem has the same sign as the dividend. Or, as it is put in the Prelude documentation, quot is integer division truncated toward zero and div is integer division truncated toward negative infinity.
How about no div or mod build-ins?
No build-ins, 36 32 31 bytes
a#b|a<b=(a,0)|m<-a-b=(+1)<$>m#b
Try it online! Example usage: 13#2 returns (1,6), that is the mod result is first and the div result second. If a is smaller b, then a mod b is a and a div b is 0, so (a,0) is returned. Otherwise recursively compute mod and div of a-b and b, add 1 to the division result and keep the remainder.
Adding 1 to the division result is achieved by using <$>, which is commonly used as map to map functions over lists, but works on tuples too, however the function is applied to the second tuple element only.
Edit: Saved one byte thanks to xnor!
APL (Dyalog), 5 bytes
-2 bytes thanks to @ngn
⌊÷,|⍨
This is an atop (2-train) of a fork (3-train), where the atop's right tine is a derived function (the result of an operator applied to a function):
result
↑┌──────────┐
││ ┌────┐│┌──────┐ (derived function)
│↓ │ ↓│↓ │╱
┌───┐ ┌───┐ ┌───┐ ╔═══╤═══╗
│ ⌊ │ │ ÷ │ │ , │ ║ | │ ⍨ ║
└───┘ └───┘ └───┘ ╚═══╧═══╝
↑ ↑ ↑ ↑ ╲
left argument ┴─────────────────┘ (operator)
└─────────┴ right argument
⌊ floor of
÷ division
, catenated to
| division remainder
⍨ with swapped arguments (APL modulus is "backwards")
BitCycle, 146 79 64 bytes
Just realized a whole section of my original code was unneccessary. Huge reduction!
v <>!
A\B^^=
? D^>^<
>\v^~ D@
>/ C/
> C ^
A/B v
^ <
? D^
The program takes input in unary from the command line, with the divisor first. It outputs the quotient and remainder in unary, separated by a 0. For example, here's a=11, b=4, a/b=2, a%b=3:
C:\>python bitcycle.py divmod.btc 1111 11111111111
110111
Ungolfed, in action
Here's my ungolfed version computing a=3, b=5 with animation turned on (sorry about the glitchiness):
Attempt at an explanation
The explanation applies to the ungolfed version. Before you tackle it, I highly recommend you read the Esolangs page to get a feel for how the language works.
The algorithm goes like this:
- Run an outer loop until the program is terminated.
- Run an inner loop over the bits of the divisor, pairing them off with bits from the dividend.
- If all bits of the divisor have matching dividend bits, output a single bit.
- If not all bits of the divisor have matching dividend bits, output the separator
0followed by what dividend bits there were, then terminate.
- Run an inner loop over the bits of the divisor, pairing them off with bits from the dividend.
The heart of the code is the relationships among the collectors (the uppercase letters). Since there are multiple separate collectors with each letter, let's refer to them as A1, A2, B1, B2, etc., numbering from top to bottom.
A1andA2hold the divisor and dividend, respectively, at the beginning of the main loop.- The inner loop peels off one bit at a time from the divisor and the dividend.
- The rest of the divisor, if any, always goes into
B1. - If both the divisor and dividend were nonempty, one bit goes into
C1and one intoC3. The rest of the dividend goes intoB2. - If only the divisor was nonempty, we've reached the end of the dividend, and it's time to print the remainder. The bit from the divisor goes into
C2. - If only the dividend was nonempty, we've reached the end of the divisor; it's time to process the bits in
C3orC2for output. The rest of the dividend goes intoC4.
- The rest of the divisor, if any, always goes into
- If there are any bits in the
Bcollectors, they cycle their contents back around to theAcollectors and continue in the inner loop. - Once the
AandBcollectors are all empty, theCcollectors open and we proceed to the processing stage:C1andC4dump their contents (the divisor and the remaining dividend, respectively) intoD1andD3.- If
C2is empty, we're still printing the quotient.- The contents of
C3go up to the top right=switch. The first1bit passes straight through to!and is output. - When the
1bit passes through, it activates the switch to point rightward, which sends all the subsequent bits off the board.
- The contents of
- If
C2is not empty, we're printing the remainder.- The first bit of
C2is negated to a0and passed through the switch. The0goes on to!and is output. - When the
0bit passes through, it activates the switch to point leftward. Now all the bits fromC3go leftward from the switch and are redirected around into the!, outputting the entire remainder. - A copy of the first bit from
C2is also sent intoD2.
- The first bit of
- Now the
Dcollectors open.- If there is anything in
D2, that means we just printed the remainder. The bit fromD2hits the@, which terminates the program. - Otherwise, the contents of
D1andD3loop back intoA1andA2respectively, and the main loop starts over.
- If there is anything in
brainfuck, 43 41 bytes
,<,[>->+<[>]>>>>+<<<[<+>-]<<[<]>-]>>.>>>.
This uses a modified version of my destructive modulus algorithm on Esolangs.
The program reads two bytes – d and n, in that order – from STDIN and prints two bytes – n%d and n/d, in that order – to STDOUT. It requires a brainfuck interpreter with a doubly infinite or circular tape, such as the one on TIO.
How it works
Before the program starts, all cells hold the value 0. After reading d from STDIN (,), moving one step left (<) and reading n from STDIN (,), the tape looks as follows.
v
A B C D E F G H J
0 n d 0 0 0 0 0 0
Next, assuming that n > 0, we enter the while loop
[>->+<[>]>>>>+<<<[<+>-]<<[<]>-]
which transforms the tape as follows.
First, >->+< advances to cell C and decrements it, then advances to cell D and increments it, and finally goes back to cell C. What happens next depends on whether the value of cell C is zero or not.
If cell C hold a positive value,
[>](go right while the cell is non-zero) will advance to cell E.>>>>+<<<advances to cell J to increment it, then goes back to cell F.Since cell F will always hold 0, the while loop
[<+>-]is skipped entirely, and<<goes back to cell D.Finally, since neither D nor C hold 0,
[<](go left while the cell is non-zero) will retrocede to cell A.If cell C holds 0, the loop
[>]is skipped entirely;>>>>+<<<advances to cell G to increment it, then goes back to cell D.At this point, D will hold d (in fact, the sum of the values in C and D will always be d), so
[<+>-](while D is positive, increment C and decrement D) will set C to d and D to 0.Finally,
<<retrocedes to cell B,[<](go left while the cell is non-zero) further left to cell A.
In both cases, >- advances to cell B and decrements it, and the loop starts over unless this zeroes it out.
After k iterations, the tape looks as follows.
v
A B C D E F G H J
0 n-k d-k%d k%d 0 0 k/d 0 k-k/d
After n iterations B is zeroed out and we break out of the loop. The desired values (n%d and n/d) will be stored in cells D and G, so >>.>>>. prints them.
QBasic 4.5, 23 bytes
INPUT a,b
?a\b,a MOD b
This speaks for itself: get two numbers (input needs to be separated by comma) and print their integer division and modulo. QBasic doesn't have a shorthand for MOD, the %symbol is reserved for defining integers.
Retina, 14 bytes
Let's abuse the input/output formats!
(.*)¶(\1)*
$#2
Takes input as b\na, in unary, using for unary digit any single non-digit, non-newline character. Outputs the quotient in decimal, immediately followed by the remainder in unary, using the same character as the input.
(.*) ¶(\1)* matches the first number , then a newline (¶ is Retina's shorthand for \n), then the first number again as many times as possible. The number of matches of the second group will be the result of the division, and the part not matched will be the remainder.
With $#2, we replace everything that was matched in the previous line with the number of captures of the second group, and get then our result.
J, 9 bytes
(<.@%,|~)
Usage:
5 (<.@%,|~) 7
0 5
5 (<.@%,|~) 1
5 0
18 (<.@%,|~) 4
4 2
255 (<.@%,|~) 25
10 5
Explanation:
In J a verb is like a function. Verbs are monadic (f x) or dyadic (x f y) and builtin verbs share the same symbol for different monadic and dyadic cases (e.g. x % y is division, % x is reciprocal).
(<.@% , |~) is a train of 3 verbs (fork in J terminology). A fork is: x (f g h) y = (x f y) g (x h y). Our verbs are:
|~-|is modulo in J, but arguments are for some reason reverse to what you'd expect. We need the adverb~to reverse the arguments:x f~ y=y f x<. @ %-x % yis division.@is a conjunction denoting function composition:x (f @ g) y=f (x g y)(J applies right-to-left).<. xis floor.,- Append.
The parenthesis are needed to form the 3-verb train. No parenthesis would parse as x <.@% (, (|~ y)).
dc, 12 bytes
?sadla/rla%f
Explanation:
? # Read input as space-separated integers, push to stack
sa # Store second to register a
d # Duplicate first
la # Load second
/ # Push first / second
r # Swap (stack now first/second, first)
la # Load second
% # Push first % second
f # Print stack (first/second, first%second, but in reverse)
With builtins, it's just ?~f. I also tried reading each integer on its own line, but it's the same length (?d?dsa/rla%f).
Ruby, 27 bytes
a,b=$<.map &:to_i
p a/b,a%b
Reads from standard input, stops when it reaches EOF, and only considers the two integers on the first two lines of its input.
Cubix, 12 13 bytes
;W@o,I|\S%;O
Which maps onto the following cube
; W
@ o
, I | \ S % ; O
. . . . . . . .
. .
. .
Explanation with steps as executed
,I|I, - starts with an superflous integer divide, gets the first integer from input, reflects back and gets the next integer from input, then divides again
O; - Output the result of the integer division and pop it
% - do the mod. This could be done later, but ended up here
S\o - Add space character to stack, redirect up and output space
W; - Shift left and pop the space from the stack
O|@ - Output the mod previously calculated, pass through the horizontal reflector and halt.
C, 21 bytes
#define f(a,b)a/b,a%b
A macro that replaces f(a,b) with the 2 terms comma separated. Though you'd better be passing it to a function or else there's no way to pick the 2 apart.
QBIC, 12 bytes
::?a'\`b,a%b
Explanation:
:: Gets two integers from the command line, a and b
? PRINT
a'\`b Integer division in QBasic is '\', however, '\' is the command for ELSE in QBIC
To tell QBIC not to swap in ELSE at the '\', we need a code literal.
Everything from the ' to the `is passed on to QBasic without being parsed.
,a%b Also print a MOD b
Lua, 40 Bytes
a=arg;io.write(a[1]//a[2],",",a[1]%a[2])
OIL, 134 106 103 102 bytes
Takes the input from stdin, the two numbers seperated by a newline. Outputs the result of the integer division, then a newline, and then the remainder.
This is one of the most complicated OIL programs I've ever written, as OIL lacks builtins for division, remainder, addition, substraction, and so on. It works with the primitive way of doing division: repeated nested decrementation.
I present the code in an annotated format, with comments in the style of scripting languages. Before executing, the comments have to be removed.
5 # read input into lines 0 and 2
5
2
0 # the zero to compare to (nops)
1 # make a backup of the second input at line 3
2
3
10 # check if the second input is 0. %
4
2
24 # if so, jump to 24 (marked with §)
13 # else, go on
10 # check if the first input is zero &
4
31 # if so, jump to 31 (marked with $)
18 # else, go on
9 # decrement both numbers
9
2
6 # jump to line 8 (marked with %)
8
8 # increment the value in line 1 (initially a zero) §
1
1 # "restore the backup"
3
2
6 # jump to line 13 (marked with &)
13
10 # is the second number zero? $
4
2
42 # if so, jump to 42 (marked with +)
36 # else go on
9 # decrement both the second number and the backup
2
9
3
6 # jump to 31 (marked with $)
31
4 # print the division +
1
11 # a newline
4
3 # and the remainder (from the backup)
edit: Shaved off 3 more bytes by moving a "constant" to a one-digit location (less bytes to reference), and then implicit-ing 2 zero-locations (By using an empty line instead. One of them I could have done before).
edit: And another byte by making the initial zero implicit. We really only need a single literal zero.
sed, 36 bytes
35 bytes of code, +1 for the -r flag.
:a;s/^(1+)( 1*)\1/\1\2x/;ta;s/.* //
Takes input in unary, space-separated, with the smaller number first. Outputs as unary, with the quotient first in 1s and the remainder second in xs. (If this isn't acceptable, let me know and I'll change it to space-separated 1s like the input.)
Explanation
:a; Define label a
s/ / /; Perform this substitution:
^(1+) Match the first unary number...
( 1*) ... followed by a space and 0 or more 1s...
\1 ... followed by the the first group again
\1\2x Keep the first two parts unchanged; replace the third
with an x
ta; If the substitution succeeded, goto a
s/.* // After the loop is over, remove the first number
><>, 27 26 16 + 1 = 17 bytes
:r:{%:n','o-$,n;
Note
- Input using the
-vflag, see TIO for an example. - This outputs the remainder first, then a comma and lastly the integer division.
Explanation
Note that the stack starts as A, B, where A and B represent the first and second input, because of the -v flag used.
:r:{%:n','o-$,n; # Explanation
:r:{ # Do some stack modifications to prepare it for
# next part
# (Stack: B, A, A, B)
% # Take the modulo of the top two items
# (Stack: B, A, A%B)
: # Duplicate it
# (Stack: B, A, A%B, A%B)
n # Pop once and output as number
# (Stack: B, A, A%B)
','o # Print separator
# (Stack: B, A, A%B)
- # Subtract the modulo from the first input
# (Stack: B, A-A%B)
$, # Swap the two inputs so they are back in order
# and divide, so we get an integer
# (Stack: floor(A/B))
n; # Output that as a number and finish.
Ouroboros, 15 bytes
r.r.@/Inao\%n1(
Takes the numbers in reverse order (e.g. 10 42). Try it here.
Explanation
r.r. Read a number, duplicate, read a number, duplicate
@ Rotate a copy of the first number to the top of the stack
/I Divide and truncate to integer
n Output as number
ao Push 10 and output as character (newline)
\% Swap the remaining two values and take the mod
n Output as number
1( Push 1 and swallow that many characters from the end of the program,
halting execution
Cardinal, 34 32 31 bytes
%:~:v
,0.M#
-
-
>8\ < <
^+/'Jx^
Input is in the format b first, a second
Output is in the format a%b, a/b
Explanation:
%:~:v
#
Sets second input as active value, first input as inactive value then sends this pointer in two directions
,0.M
Gets the active value mod inactive value, outputs then outputs a space
.
-
-
>8\ < <
^+/'Jx^
Counts the number of times the inactive value can be subtracted from the active value before it falls to <=0 before outputting the count.
brainfuck, 47 bytes
>,>,-[+<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>>>>]<<.>.
Input/output in byte-values.
Try it online! - Computes 109,10->10,9, which in characters corresponds to m,\n->\n,\t
This is simply the esolang brainfuck divmod algorithm, with a wrapper for doing input/output and dealing with the case where divisor=1. I'm sure that someone could modify the algorithm to make it work with any input without the need for my boilerplate, but at least now there's a brainfuck answer^^
Jellyfish, 14 bytes
p
m
,|S
% i
Ei
Explanation
Jellyfish is a beautiful language when it comes to applying multiple functions to the same input. The language is 2D and all binary functions look south for one input and east for another. So by approaching one value from the west and from the north, we can feed it to two functions without having to duplicate it in the code.
The two is in the program are replaced with the two input values when the program starts. Now % is division. It takes one input directly from the east, and when going south it hits the E which redirects that search east as well. So both inputs get fed to % as arguments.
| is the built-in for modulo, which basically does the same thing, but ends up looking south for both in puts.
We concatenate both results into a pair with ,. Then m is the floor function (which we need because % is floating-point division) and finally we print the result with p.
Microscript, 11 bytes
ivissCl/pl%
Brain-Flak, 168 148 110 bytes
I guess I should have checked the Wiki first
(({})(<({}(<(({})<>)>))<>([()]{()<(({})){({}[()])<>}{}>}{}<><{}{}>)>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{}<>)
Format:
Input: Output:
A (18) remainder (2)
B (4) division (4)
(({})(< # Copy A
({}(< # Pick up A
(({})<>) # Copy B to the other stack
>)) # Put A on top of a 0 on the second stack
# At this point the stacks look like this: A
0
B B
^
<>([()]{()<(({})){({}[()])<>}{}>}{}<><{}{}>) # Positive division from the wiki
>)) # Put down A on top of a 0
# The stack now: A
0
Div B
^
<>{(({})){({}[()])<>}{}}{}<>([{}()]{}<>) # Modulo from the wiki
Batch, 37 bytes
@set/ad=%1/%2,m=%1%%%2
@echo %d% %m%
ForceLang, 106 bytes
def N io.readnum()
def S set
S W gui.show
S a N
S b N
W S c math.floor a.mult b.pow -1
S c c.mult b
W a+-c
Math++, 18 bytes
?>a
?>b
_(a/b)
a%b
CJam, 7 bytes
q_~/n~%
n = print with trailing newline
-2 thanks to Martin Ender.
-3 thanks to Peter Taylor and Basic Sunset.I was thinking eval first then the rest.
PowerShell, 38 31 bytes
$a,$b=$args;($a-$a%$b)/$b;$a%$b
Sheesh, this is icky. So, PowerShell (helpfully) returns floating point values when doing division if it doesn't divide evenly. Sometimes, this is a Good Thing, but other times (like here) it's very not. So, you'd figure "Oh, let's just toss an [int] cast and call it good, right?" Nope. Casting from a [double] to an [int] in PowerShell does banker's rounding, so for input 5, 7 we would get 1 back, not 0. As a result, we need to subtract the remainder (from the modulo), then calculate the division, and then calculate the modulo again. Yay!
Both results are left on the pipeline, and output is implicit.
Saved 7 bytes thanks to PeterTaylor being smarter than me.
MATL, 12 10 bytes
Qt:ie=&fhq
Input is a, then b. Output is remainder, then quotient.
Explanation
This avoids both modulo and division. Instead it uses array reshaping:
- Build an array of
a+1nonzero elements. - Reshape as a 2D array of
brows. This automatically pads with zeros if needed. - The row and column indices of the last nonzero entry, minus
1, are respectively the remainder and quotient.
Consider for example a=7, b=3.
Q % Input a implicitly. Push a+1
% STACK: 8
t: % Duplicate. Range from 1 to that
% STACK: 8, [1 2 3 4 5 6 7 8]
ie % Input b. Reshape as a matrix with b rows (in column major order)
% STACK: 8, [1 4 7;
2 5 8]
3 6 0]
= % Compare for equality
% STACK: [0 0 0;
0 0 1;
0 0 0]
&f % Row and column indices (1-based) of nonzero element
% STACK: 2, 3
hq % Concatenate. Subtract 1. Implicitly display
% STACK: [1 2]
JavaScript (ES6), 17 bytes
Thanks to @Arnauld for golfing off one byte
x=>y=>[x/y|0,x%y]
Receives input in format (x)(y)
Gets floor of x/y by performing bitwise or
Gets remainder by x%y
Puts both values in an array so that they can both be returned
Elixir, 24 bytes
&{div(&1,&2),rem(&1,&2)}
Anonymous function which uses the capture operator and returns a tuple containing the results.
Full program with test cases (and yes, the . in the function call is required!):
f =
&{div(&1,&2),rem(&1,&2)}
# test cases:
IO.inspect f.(5,7) # 0,5
IO.inspect f.(5,1) # 5,0
IO.inspect f.(18,4) # 4,2
IO.inspect f.(255,25) # 10,5
Try it online on Elixir Playground.
PHP, 35 Bytes
[,$a,$b]=$argv;echo$a/$b^0,_,$a%$b;
05AB1E, 5 bytes
÷²¹%‚
05AB1E has a bug, so implicit input doesn't work :( Emigna noted that inputs are often pushed in reverse.
Wonder, 13 bytes
@@[/#1#0%#1#0
Usage:
((@@[/#1#0%#1#0)10)5
Simply a curried lambda that returns a list with both the division and modulus. I'm looking for a golfier way to do this, something that doesn't involve lambdas.
Be sure to do tK1000 beforehand to view list items in the output.
Java 8, 18 Bytes
(a,b)->a/b+","+a%b
This is a lambda expression of the type BiFunction<Integer, Integer, String>.
I'm surprised... this is actually a fairly concise solution for Java. Go lambda expressions!
Mathematica, 20 18 bytes
⌊#/#2⌋@Mod@##&
Minor abuse of the flexible output rules: the result is given as div[mod], which will remain unevaluated. The individual numbers can be extracted with result[[0]] and result[[1]].
And hey, it's only one byte longer than the ridiculously named built-in QuotientRemainder.
Mathematica, actually has a neat way to apply multiple functions to the same input, but it's three bytes longer:
Through@*{Quotient,Mod}
Brachylog, 6 bytes
{÷|%}ᶠ
Explanation
We abuse the metapredicate ᶠ findall to apply two different predicates to the Input list of two arguments:
{ }ᶠ Findall for the Input [A,B] :
÷ Integer division
| Or…
% Modulo
Labyrinth, 11 bytes
?:?:}/!\{%!
Explanation
?: Read a and duplicate.
?: Read b and duplicate.
} Move a copy of b over to the auxiliary stage.
/ Compute a/b.
! Print it.
\ Print a linefeed.
{ Get back the other copy of b.
% Compute a%b.
! Print it.
The IP then hits a dead end, turns around and the program terminates due to the attempted division by zero when % is executed again.

