Division and remainder

36

4

This challenge, while probably trivial in most "standard" languages, is addressed to those languages which are so esoteric, low-level, and/or difficult to use that are very rarely seen on this site. It should provide an interesting problem to solve, so this is your occasion to try that weird language you've read about!

The task

Take two natural numbers a and b as input, and output two other numbers: the result of the integer division a/b, and the remainder of such division (a%b).

This is : shortest answer (in bytes), for each language, wins!

Input/Output

  • 0<=a<=255, 1<=b<=255. Each of your inputs (and outputs too) will fit in a single byte.
  • You may choose any format you like for both input and output, as long as the two numbers are clearly distinguishable (e.g. no printing the two results together without a delimiter)

Examples

a,b->division,remainder
5,7->0,5
5,1->5,0
18,4->4,2
255,25->10,5

Note: Builtins that return both the result of the division and the remainder are forbidden. At least show us how your language deals with applying two functions to the same arguments.

Note 2: As always, an explanation of how your code works is very welcome, even if it looks readable to you it may not be so for someone else!


The Catalogue

The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

## Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

## Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

## Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the snippet:

## [><>](https://esolangs.org/wiki/Fish), 121 bytes

/* Configuration */

var QUESTION_ID = 114003; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 8478; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });  
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];
  
  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });
    
    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    else console.log(body);
  });
  
  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;
    
    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    lang = jQuery('<a>'+lang+'</a>').text();
    
    languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
body {
  text-align: left !important;
  display: block !important;
}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 500px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f">
<div id="language-list">
  <h2>Shortest Solution by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>

Leo

Posted 2017-03-27T12:38:57.923

Reputation: 8 482

Can I reverse the arguments, i.e. instead of providing a b providing b a instead? – Erik the Outgolfer – 2017-03-27T13:29:40.540

@EriktheOutgolfer: You may choose any format you like for both input and output, as long as the two numbers are clearly distinguishable – Emigna – 2017-03-27T13:30:01.210

@Emigna Yeah, I was not sure if reversing didn't make them indistinguishable though. – Erik the Outgolfer – 2017-03-27T13:32:58.840

@EriktheOutgolfer if you know that they need to be reversed you have no problem in distinguishing them :) – Leo – 2017-03-27T13:45:07.837

Unfortunately, the BF algorithm doesn't work if the divisor is 1. – mbomb007 – 2017-03-27T13:45:49.470

@mbomb007 Which BF algorithm? – Leo – 2017-03-27T13:47:59.070

The BF algorithm for divmod, of course. https://esolangs.org/wiki/Brainfuck_algorithms#Divmod_algorithm

– mbomb007 – 2017-03-27T13:56:08.000

The code snippet doesn't appear to display anything? (Actually, it displays "Winners by Language

Language User Score" but nothing else.) – Brian McCutchon – 2017-03-27T22:30:41.230

@BrianMcCutchon strange, it worked fine earlier... unfortunately, I can't check it now since I'm from my phone. If anyone knows how to fix it feel free to edit the question, otherwise I'll have a look at it tomorrow morning. – Leo – 2017-03-27T22:42:26.157

If it helps, when I run it, I get "[Error] Error: Syntax error, unrecognized expression: QBasic (<a href="https://drive.google.com/open?id=0B0R1Jgqp8Gg4UVliSTE0MzdLcEU" rel="nofollow noreferrer">Get it here</a>) 4.5". – Brian McCutchon – 2017-03-27T23:17:33.727

This error message contains part of the title of an answer to this question. (Are you trying to eval it?) I suggested an edit to said answer to make it follow your format as a temporary solution.

– Brian McCutchon – 2017-03-27T23:23:35.643

I'd recommend adding that input will always be positive. Negative modulo is arbitrary in many languages, some return remainder while others return inverse-remainder (or x-rem). For example in C (-5)%(3) is -2 whereas on Wolfram|Alpha (-5)%(3) is 1. There is no defined standard. – Albert Renshaw – 2017-04-11T20:38:35.437

@AlbertRenshaw 0<=a<=255, 1<=b<=255, it's right there in the Input/Output rules ;) – Leo – 2017-04-11T20:40:36.160

@Leo Haha! Thank you, I just cmd+f "positive" and "negative", silly me – Albert Renshaw – 2017-04-11T20:41:10.007

If this could be accomplished in a single operation by a method that isn't a divmod or meant to be a mathematical operation, would that be forbidden? I'm speaking of things like self-modifying code and abusing base-conversion... – 640KB – 2019-12-11T21:23:59.387

Answers

23

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

Divmod running in BitCycle

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 0 followed by what dividend bits there were, then terminate.

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.

  • A1 and A2 hold 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 C1 and one into C3. The rest of the dividend goes into B2.
    • 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 C3 or C2 for output. The rest of the dividend goes into C4.
  • If there are any bits in the B collectors, they cycle their contents back around to the A collectors and continue in the inner loop.
  • Once the A and B collectors are all empty, the C collectors open and we proceed to the processing stage:
    • C1 and C4 dump their contents (the divisor and the remaining dividend, respectively) into D1 and D3.
    • If C2 is empty, we're still printing the quotient.
      • The contents of C3 go up to the top right = switch. The first 1 bit passes straight through to ! and is output.
      • When the 1 bit passes through, it activates the switch to point rightward, which sends all the subsequent bits off the board.
    • If C2 is not empty, we're printing the remainder.
      • The first bit of C2 is negated to a 0 and passed through the switch. The 0 goes on to ! and is output.
      • When the 0 bit passes through, it activates the switch to point leftward. Now all the bits from C3 go leftward from the switch and are redirected around into the !, outputting the entire remainder.
      • A copy of the first bit from C2 is also sent into D2.
  • Now the D collectors open.
    • If there is anything in D2, that means we just printed the remainder. The bit from D2 hits the @, which terminates the program.
    • Otherwise, the contents of D1 and D3 loop back into A1 and A2 respectively, and the main loop starts over.

DLosc

Posted 2017-03-27T12:38:57.923

Reputation: 21 213

that is awesome – Evan Carslake – 2017-03-30T17:33:20.593

"The program takes input in unary from the command line": That looks like binary to me? – 2xsaiko – 2017-03-30T18:36:28.893

Whoops. Because the output looked like binary, I though the input should be too. Then I read the text. Nevermind. :P – 2xsaiko – 2017-03-31T15:37:02.327

15

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.

Try it online!

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.

Dennis

Posted 2017-03-27T12:38:57.923

Reputation: 196 637

13

Funciton, 224 108 bytes

Byte count assumes UTF-16 encoding with BOM.

 ┌──┬───┐
┌┴╖╓┴╖ ┌┴╖
│%╟║f╟┐│÷╟┘
╘╤╝╙─╜│╘╤╝
 └────┴─┘

Try it online!

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.

Martin Ender

Posted 2017-03-27T12:38:57.923

Reputation: 184 808

10

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

Try it online!

fəˈnɛtɪk

Posted 2017-03-27T12:38:57.923

Reputation: 4 166

10

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

Try it online!

Adám

Posted 2017-03-27T12:38:57.923

Reputation: 37 779

How did you make that cool diagram? – emiflake – 2017-03-27T20:19:32.787

2

@WolfgangTS Painstakingly. Dyalog APL comes with ability to make basic tree diagrams of tacit functions. Try it online! I started with that...

– Adám – 2017-03-27T20:23:13.060

Ouch, looks very difficult. I don't have the patience for that I'm afraid, haha – emiflake – 2017-03-27T21:48:05.750

shorter: ⌊÷,|⍨ – ngn – 2017-03-28T11:05:10.560

@ngn Ouch, you got me. Happy to see that you're still here. – Adám – 2017-03-28T11:05:37.940

@WolfgangTS that's what AHK is for – Stan Strum – 2017-09-11T19:50:06.473

7

Brachylog, 6 bytes

{÷|%}ᶠ

Try it online!

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

Fatalize

Posted 2017-03-27T12:38:57.923

Reputation: 32 976

7

MATL, 12 10 bytes

Qt:ie=&fhq

Input is a, then b. Output is remainder, then quotient.

Try it online!

Explanation

This avoids both modulo and division. Instead it uses array reshaping:

  1. Build an array of a+1 nonzero elements.
  2. Reshape as a 2D array of b rows. This automatically pads with zeros if needed.
  3. 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]

Luis Mendo

Posted 2017-03-27T12:38:57.923

Reputation: 87 464

2This is a fine example of lateral thinking, nice work! – Leo – 2017-03-27T14:34:12.777

6

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}

Martin Ender

Posted 2017-03-27T12:38:57.923

Reputation: 184 808

1You know it's bad when you language creates built-ins that simply combines built-ins… – Fatalize – 2017-03-27T13:08:06.197

1@Fatalize Is it? I find divmod built-ins quite useful, and Mathematica is by far not the only language to have one. – Martin Ender – 2017-03-27T13:11:29.500

8@Fatalize, a lot of the same work is required to compute quotients as is required to compute remainders. If both results are to be used, a properly-engineered quotRem builtin can save significant time over calling quot and rem separately. – Julian Wolf – 2017-03-27T14:26:17.130

6

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!

Socratic Phoenix

Posted 2017-03-27T12:38:57.923

Reputation: 1 629

You can golf a byte by using a currying lambda a->b-> instead of (a,b)->: Try it online.

– Kevin Cruijssen – 2020-01-21T11:17:02.727

6

05AB1E, 5 bytes

÷²¹%‚

Try it online!

05AB1E has a bug, so implicit input doesn't work :( Emigna noted that inputs are often pushed in reverse.

Erik the Outgolfer

Posted 2017-03-27T12:38:57.923

Reputation: 38 134

You could do ÷²¹%) for 5 bytes.

– Emigna – 2017-03-27T13:23:28.070

@Emigna I dunno if it's valid though. Wait, how did that work? – Erik the Outgolfer – 2017-03-27T13:26:15.353

1I don't see why it wouldn't be valid. It works because implicit inputs are pushed to the stack in the reverse order of what you'd assume in cases like this. – Emigna – 2017-03-27T13:27:29.057

@Emigna I have asked OP if I can reverse the arguments. – Erik the Outgolfer – 2017-03-27T13:31:37.813

2I take You may choose any format you like for both input and output, as long as the two numbers are clearly distinguishable to mean that you can decide that the inputs are taken as divisor, dividend. You could just specify "Input are taken as divisor, dividend" in the answer and they'll be clearly distinguishable :) – Emigna – 2017-03-27T13:34:02.613

s‰ also works, retaining args order, or with swapped arguments. 2-byte and 1-byte each respectively. – Magic Octopus Urn – 2017-04-17T16:26:18.743

@carusocomputing Divmod builtins aren't allowed. – Erik the Outgolfer – 2017-04-17T16:27:58.637

6

Jellyfish, 14 bytes

p
m
,|S
% i
Ei

Try it online!

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.

Martin Ender

Posted 2017-03-27T12:38:57.923

Reputation: 184 808

6

Cubix, 12 13 bytes

;W@o,I|\S%;O

Which maps onto the following cube

    ; W
    @ o
, I | \ S % ; O
. . . . . . . .
    . .
    . .

Try it here

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.

MickyT

Posted 2017-03-27T12:38:57.923

Reputation: 11 735

Beat me by two minutes. Nice answer! – Luke – 2017-03-27T19:17:33.970

@Luke Thanks, thought I could get another one off, but proving elusive – MickyT – 2017-03-27T19:22:39.607

6

Brain-Flak, 56 54 bytes

({}<>)<>([()]{()<(({})){({}[()])<>}{}>}<><([{}()]{})>)

Try it online!

-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...

0 '

Posted 2017-03-27T12:38:57.923

Reputation: 3 439

5

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.

Luke

Posted 2017-03-27T12:38:57.923

Reputation: 4 675

I think you mean cell A1 and B1 not A1 and A2 – fəˈnɛtɪk – 2017-03-27T13:57:24.960

Yes, thanks. Fixed now – Luke – 2017-03-27T14:09:41.223

Save 1 byte with FLOOR(A1/B1;1) instead of QUOTIENT(A1;B1) – Engineer Toast – 2017-03-30T12:36:11.233

Because the input is always a Natural number, I think you can replace FLOOR(A1/B1;1) with `INT(A1/B1)' to save 4 more bytes – Wernisch – 2017-09-20T13:39:42.987

5

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)

Try it online!

(({})(<           # 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

Riley

Posted 2017-03-27T12:38:57.923

Reputation: 11 345

Golf – Post Rock Garf Hunter – 2017-03-27T14:52:45.727

5

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

DLosc

Posted 2017-03-27T12:38:57.923

Reputation: 21 213

4

Python 2, 20 bytes

lambda a,b:(a/b,a%b)

Try it online!

Built-in, 6 bytes

divmod

Try it online!

Rod

Posted 2017-03-27T12:38:57.923

Reputation: 17 588

4

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.

L3viathan

Posted 2017-03-27T12:38:57.923

Reputation: 3 151

Great work! That's exactly the kind of answer I hoped this challenge would receive :) Just a note: you are guaranteed that the divisor will always be strictly positive, so you don't need to check for a division by 0 ;) – Leo – 2017-03-27T14:12:39.617

@Leo I'm guaranteed that the divisor will always be strictly positive at the beginning. It won't work if I take the division by zero part out, this case can happen even when the "actual" division is a normal one. If I remember correctly this occurs when the remainder is zero. – L3viathan – 2017-03-27T14:38:47.610

I'm talking about the check on line 4, not the one on line 12... Doesn't it execute just once at the start of the program? – Leo – 2017-03-27T14:41:30.977

@Leo Done, almost 30 characters less, thanks! – L3viathan – 2017-03-27T15:02:17.303

4

Jelly, 3 bytes

:,%

Try it online!

Erik the Outgolfer

Posted 2017-03-27T12:38:57.923

Reputation: 38 134

Darn, I was just going to post this, I tested it a few extra times and got ninja'd :( good job! – HyperNeutrino – 2017-03-27T13:06:23.163

4

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.

Try it online!

(.*) ¶(\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.

Leo

Posted 2017-03-27T12:38:57.923

Reputation: 8 482

Haha, quite right, I clearly shouldn't be writing programs that late in the evening. – FryAmTheEggman – 2017-03-30T18:37:29.650

4

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

Try it online!

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

Tom291

Posted 2017-03-27T12:38:57.923

Reputation: 313

3

Labyrinth, 11 bytes

?:?:}/!\{%!

Try it online!

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.

Martin Ender

Posted 2017-03-27T12:38:57.923

Reputation: 184 808

3

><>, 27 26 16 + 1 = 17 bytes

:r:{%:n','o-$,n;

Note

  • Input using the -v flag, see TIO for an example.
  • This outputs the remainder first, then a comma and lastly the integer division.

Try it online!

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.

Luke

Posted 2017-03-27T12:38:57.923

Reputation: 4 675

How can you provide input values up to 255? – Leo – 2017-03-27T14:43:52.917

Just use higher ASCII/Unicode values. That way, į becomes 255. – Luke – 2017-03-27T14:46:14.927

Ok, nice :) By the way, wouldn't it be shorter to take input numbers from command line directly with the -v flag? – Leo – 2017-03-27T15:18:57.520

It would, but I couldn't get that to work on TIO, so I settled with this solution. It would save 8 bytes - 1 (for the -v flag). – Luke – 2017-03-27T15:23:30.817

Here you are :) – Leo – 2017-03-27T15:42:19.950

3

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!

Laikoni

Posted 2017-03-27T12:38:57.923

Reputation: 23 676

2Your second solution can shave a byte using <$> on a tuple to act on its second element :a#b|a<b=(a,0)|m<-a-b=(+1)<$>m#b. – xnor – 2017-03-28T00:20:28.677

3

C, 32 bytes

f(a,b){printf("%d %d",a/b,a%b);}

Try it online!

Abel Tom

Posted 2017-03-27T12:38:57.923

Reputation: 1 150

3

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.

Try It Online

Bijan

Posted 2017-03-27T12:38:57.923

Reputation: 781

3

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

Jan Drozen

Posted 2017-03-27T12:38:57.923

Reputation: 491

Welcome to PPCG! I have never used Prolog before, but noticed there are spaces around :- in the last line but not on the others. Are they required there for some reason? The same goes for E + 1 while F-S suggest there are no spaces needed. – Laikoni – 2017-03-31T11:20:04.470

Laikoni: You are definitely right! I've just removed the spaces and updated final byte count. – Jan Drozen – 2017-03-31T12:19:01.337

2

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

Suever

Posted 2017-03-27T12:38:57.923

Reputation: 10 257

2

Gol><>, 11 bytes

I:I:@$S,N%h

Online interpreter

Erik the Outgolfer

Posted 2017-03-27T12:38:57.923

Reputation: 38 134

2

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

DLosc

Posted 2017-03-27T12:38:57.923

Reputation: 21 213

2

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.

Redouane Red

Posted 2017-03-27T12:38:57.923

Reputation: 311

2You don't have to use stdin and stdout for I/O. Typically, the golfiest Ruby solutions are anonymous lambdas: try ->a,b{[a/b,a%b]} for 16 bytes! – m-chrzan – 2017-03-27T21:25:45.353

2

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)

Try it online!

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

Brian McCutchon

Posted 2017-03-27T12:38:57.923

Reputation: 503

2

Alice, 12 10 bytes

 \%.\
O:io

Try it online!

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...

Martin Ender

Posted 2017-03-27T12:38:57.923

Reputation: 184 808

I'm glad you wrote this answer :) I've tried to play with the layout and came up with this alternative solution for the same byte count (but maybe a weirder flow)

– Leo – 2017-04-11T21:04:45.807

@Leo Ah nice. I had some earlier solutions using 1,, but they were longer. Also, nice work figuring out 1, (as opposed to ~) on your own! :D – Martin Ender – 2017-04-11T21:22:15.203

1

Cardinal, 34 32 31 bytes

%:~:v
,0.M#
-
-
>8\ < <
^+/'Jx^

Try it online!

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.

fəˈnɛtɪk

Posted 2017-03-27T12:38:57.923

Reputation: 4 166

1

Batch, 37 bytes

@set/ad=%1/%2,m=%1%%%2
@echo %d% %m%

Neil

Posted 2017-03-27T12:38:57.923

Reputation: 95 035

Dang, I'm happy Peter gave me a golf, or this would've been shorter than PowerShell and I would've been embarrassed! :D – AdmBorkBork – 2017-03-27T18:35:27.373

1

Microscript, 11 bytes

ivissCl/pl%

SuperJedi224

Posted 2017-03-27T12:38:57.923

Reputation: 11 342

1

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^^

Leo

Posted 2017-03-27T12:38:57.923

Reputation: 8 482

1

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

Greg Martin

Posted 2017-03-27T12:38:57.923

Reputation: 13 940

1

Pyke, 3 bytes

'f%

Try it online!

Blue

Posted 2017-03-27T12:38:57.923

Reputation: 26 661

1

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

steenbergh

Posted 2017-03-27T12:38:57.923

Reputation: 7 772

1

Pip, 8 bytes

Pa//ba%b

Try it online!

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.

steenbergh

Posted 2017-03-27T12:38:57.923

Reputation: 7 772

1

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.

steenbergh

Posted 2017-03-27T12:38:57.923

Reputation: 7 772

1

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 % y is division. @ is a conjunction denoting function composition: x (f @ g) y = f (x g y) (J applies right-to-left). <. x is floor.

  • , - Append.

The parenthesis are needed to form the 3-verb train. No parenthesis would parse as x <.@% (, (|~ y)).

kaoD

Posted 2017-03-27T12:38:57.923

Reputation: 584

1

ReRegex, 75 Bytes.

#import math
div<(_*),\1_+(,(_*))?>/$3/s(\d+),(\d+)e/$1\/$2,$1%$2/s#input
e

Explination

This is made up of the following regex match and replaces...

  • div<(_*),\1_*(,(_*))?> / $3
  • s(\d+),(\d+)e / $1/$2,$1%$2

And the code 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, almost all of it is taken care of by the math library, However, the latest version contains an issue with the fact that integer division is actually ceiling, instead of floor'd division. So the first replacement corrects that.

Currently no TIO, but the GitHub is available.

ATaco

Posted 2017-03-27T12:38:57.923

Reputation: 7 898

1

I, 5 bytes

/.m,%

/ divide the arguments

.m apply minimum

,% append modulus

Try it online!

Adám

Posted 2017-03-27T12:38:57.923

Reputation: 37 779

1

Forth, 4 bytes

/MOD

Top of stack will be the quotient, then the remainder.

2xsaiko

Posted 2017-03-27T12:38:57.923

Reputation: 699

1

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

pizzapants184

Posted 2017-03-27T12:38:57.923

Reputation: 3 174

You can save 2 bytes with Prompt A,B:int({A/B,remainder(A,B – lirtosiast – 2017-04-06T18:42:22.777

1

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

caird coinheringaahing

Posted 2017-03-27T12:38:57.923

Reputation: 13 702

1

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.

Trÿ it online!

Explanation:

I don't know whÿ \ is the first character... Removed it and managed to save two bÿtes. Still don't know whÿ it was there in the first place. ಠ_ಠ

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 contains input1 input1.
  • $S reads another input to the stack, then stashes it in memorÿ. Stack contains input1 input1 input2, and memorÿ contains input2.
  • _ divides the top two stack values. Now the stack contains input1 input1/input2.
  • % prints the top of stack as an integer.
  • p pops the top of stack. Now the stack contains input1.
  • U pulls memorÿ onto the stack. Now the stack contains input1 input2.
  • A pushes 10 to the stack. Stack contains input1 input2 10.
  • @ prints it as ASCII (newline).
  • p pops it - stack contains input1 input2.
  • m performs modulus on the top two stack values. Stack now contains input1%input2.
  • % prints the top of stack as an integer.
  • the IP then runs off the plaÿing field, and the program terminates.

MD XF

Posted 2017-03-27T12:38:57.923

Reputation: 11 605

1

Implicit, 9 bytes

$$|/%;_@9

Try it online!

$$|/%;_@9
$$         read two integer inputs
  |        duplicate stack
   /       division
    %      print
     ;     pop
      _    modulus
       @9  print HTAB (delimiter)

MD XF

Posted 2017-03-27T12:38:57.923

Reputation: 11 605

1

Whispers v2, 77 bytes

> Input
> Input
>> 1÷2
>> ⌊3⌋
>> 1%2
>> Output 4
>> Output 5
>> Then 6 7

Try it online!

caird coinheringaahing

Posted 2017-03-27T12:38:57.923

Reputation: 13 702

1

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

TIO

user85052

Posted 2017-03-27T12:38:57.923

Reputation:

1

33, 11 bytes

OcOcsdoilro

Try it online!

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

TheOnlyMrCat

Posted 2017-03-27T12:38:57.923

Reputation: 1 079

1

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.

Kevin Cruijssen

Posted 2017-03-27T12:38:57.923

Reputation: 67 575

1

MathGolf, 4 bytes

‼/%]

Inputs in the order b a, output as a list containing two integers.

Try it online.

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

Kevin Cruijssen

Posted 2017-03-27T12:38:57.923

Reputation: 67 575

0

CJam, 7 bytes

q_~/n~%

Try it online!

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.

Erik the Outgolfer

Posted 2017-03-27T12:38:57.923

Reputation: 38 134

2You can save a few bytes by duplicating the input string before evaling it: q_~/n~% – Business Cat – 2017-03-27T14:12:27.597

0

GolfScript, 6 bytes

.~/p~%

Try it online!

I'm literally on an answer spree!

-3 thanks to Peter Taylor.

Erik the Outgolfer

Posted 2017-03-27T12:38:57.923

Reputation: 38 134

2Why evaluate so early if it forces you into such complicated stack manipulations? .~/p~% and similarly for CJam. – Peter Taylor – 2017-03-27T14:12:21.520

@PeterTaylor That is very cool. – Erik the Outgolfer – 2017-03-27T14:41:11.633

0

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.

Mama Fun Roll

Posted 2017-03-27T12:38:57.923

Reputation: 7 234

0

PHP, 35 Bytes

[,$a,$b]=$argv;echo$a/$b^0,_,$a%$b;

Jörg Hülsermann

Posted 2017-03-27T12:38:57.923

Reputation: 13 026

0

Forth, 25 bytes

: f 2dup / -rot mod ;

Try it online

Input like a b, output like remainder quotient.

mbomb007

Posted 2017-03-27T12:38:57.923

Reputation: 21 944

0

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.

adrianmp

Posted 2017-03-27T12:38:57.923

Reputation: 1 592

0

PowerShell, 38 31 bytes

$a,$b=$args;($a-$a%$b)/$b;$a%$b

Try it online!

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.

AdmBorkBork

Posted 2017-03-27T12:38:57.923

Reputation: 41 581

($a-$a%$b)/$b? – Peter Taylor – 2017-03-27T14:09:51.030

@PeterTaylor Oh. Right. facepalm – AdmBorkBork – 2017-03-27T14:41:40.610

0

Lua, 40 Bytes

a=arg;io.write(a[1]//a[2],",",a[1]%a[2])

Jörg Hülsermann

Posted 2017-03-27T12:38:57.923

Reputation: 13 026

0

Math++, 18 bytes

?>a
?>b
_(a/b)
a%b

SuperJedi224

Posted 2017-03-27T12:38:57.923

Reputation: 11 342

0

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

SuperJedi224

Posted 2017-03-27T12:38:57.923

Reputation: 11 342

0

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.

Shaun Bebbers

Posted 2017-03-27T12:38:57.923

Reputation: 1 814

0

Pyth, 7 bytes

/QKE%QK

Online interpreter

Erik the Outgolfer

Posted 2017-03-27T12:38:57.923

Reputation: 38 134

0

REXX, 20 bytes

arg a b
say a%b a//b

idrougge

Posted 2017-03-27T12:38:57.923

Reputation: 641

0

Fortran 95, 45 bytes

function f(i,j)
write(*,*)i/j,modulo(i,j)
end

Steadybox

Posted 2017-03-27T12:38:57.923

Reputation: 15 798

0

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

On-line test

manatwork

Posted 2017-03-27T12:38:57.923

Reputation: 17 865

0

Gema, 25 characters

* *=@div{*;*} @mod{$1;$2}

Sample run:

bash-4.3$ gema '* *=@div{*;*} @mod{$1;$2}' <<< '255 25'
10 5

manatwork

Posted 2017-03-27T12:38:57.923

Reputation: 17 865

0

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.

Engineer Toast

Posted 2017-03-27T12:38:57.923

Reputation: 5 769

0

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.

Try it online!


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.

Engineer Toast

Posted 2017-03-27T12:38:57.923

Reputation: 5 769

0

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. :)

640KB

Posted 2017-03-27T12:38:57.923

Reputation: 7 149

0

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
```

user85052

Posted 2017-03-27T12:38:57.923

Reputation: