39
\$\begingroup\$

Task

Given two strictly positive integers n and d as input, determine whether n is evenly divisible by d, i.e., if there exists an integer q such that n = qd.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

The output should be a truthy or a falsy value; truthy if n is divisible by d, and falsy otherwise.

Your code only has to handle integers it can represent natively, as long as it works for all signed 8-bit integers. However, your algorithm has to work for arbitrarily large integers.

You may use any programming language, but note that these loopholes are forbidden by default.

This is , so the shortest valid answer – measured in bytes – wins.

Test cases

 n,  d    output

 1,  1    truthy
 2,  1    truthy
 6,  3    truthy
17, 17    truthy
22,  2    truthy
 1,  2    falsy
 2,  3    falsy
 2,  4    falsy
 3,  9    falsy
15, 16    falsy

Leaderboard

The Stack Snippet at the bottom of this post generates the catalog 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 + 3 (-p flag) = 45 bytes

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

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

<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <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><script>var QUESTION_ID = 86149; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 48934; 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.toLowerCase(), 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 > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) 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); } }</script>

\$\endgroup\$
  • \$\begingroup\$ This conversation has been moved to chat. \$\endgroup\$ – Dennis Jul 21 '16 at 19:12

100 Answers 100

41
\$\begingroup\$

Jelly, 1 byte

This took me hours to golf.

Try it online!

\$\endgroup\$
  • 12
    \$\begingroup\$ wow that's very very complex! \$\endgroup\$ – user54200 Jul 22 '16 at 12:46
  • \$\begingroup\$ @MatthewRoh Yep. Like I said, it took me hours to come up with. :P \$\endgroup\$ – DJMcMayhem Jul 23 '16 at 20:08
29
+700
\$\begingroup\$

Brain-Flak, 72 70 64 62 58 46 bytes

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

Takes dividend and divisor (in that order) as input and prints the divisor (truthy) or nothing. Since each stack has an implicit, infinite amount of zeroes, empty output should be considered falsy.

While not stack-clean, this solution uses only a single stack.

Try it online!

Thanks to @WheatWizard for golfing off 2 bytes!

How it works

                INPUT: a (dividend), b (divisor)
                INITIAL STACK: n = a, d = b, r = 0
                               An infinite amount of zeroes follows.

{               While n is non-zero:
  (
    {}              Pop n from the stack.
    [()]            Yield -1.
    {               While the top of the stack (initially, d) is non-zero:
      (<()>)          Push 0.
    }
    {}              Pop 0. This will remove d from the stack if d = 0, leaving r
                    on top. We can think of this as performing the assignment
                    (d, r) = (r, d) if d = 0.
    <
      (
        {}              Pop d.
        [()]            Yield -1.
        <
          (
            {}              Pop r.
            ()              Yield 1.
          )               Push r + 1.
        >               Yield 0.
      )               Push d + (-1) + 0 = d - 1.
    >               Yield 0.
  )               Push n + (-1) + 0 + 0 + 0 = n - 1.
}               Each iteration decrements n, swaps d and r if d = 0, decrements d,
                and increments r.
                FINAL VALUES: n = 0
                              d = b - r
                              r = a % b if a % b > 0 else b
{}              Pop n.
{               While the top of the stack is non-zero:
  {}              Pop it.
}               This pops d and r if d > 0 (and, thus, a % b > 0) or noting at all.
{}              Pop d or a 0, leaving r if r = b and, thus, a % b = 0.

Modulus calculation, 42 bytes

The above full program can be modified in a trivial manner to calculate the modulus instead.

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

As before, this method is not stack-clean, but it uses only a single stack. A modulus of 0 will leave the stack empty, which is roughly equivalent to leaving 0; each stack contains infinite zeroes.

Try it online!

How it works

Compare the two loops of the divisibility tester and the modulus calculator.

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

The only difference is the location of {(<()>)}{}, which swaps d and r if d = 0. To calculate the modulus, we perform this swap after decrementing d and incrementing r.

This change does not affect the outcome if a %b > 0, but if a % b = 0, it leaves (n, d, r) = (0, b, 0) – rather than (n, d, r) = (0, 0, b) – on the stack.

Thus, to obtain the modulus, we only have to pop n and d with {}{}.

Stack-clean modulus calculation, 64 bytes

The 42-byte modulus algorithm is not stack-clean, so it cannot be used as is in all programs. The following version pops dividend and divisor (in that order) from the active stack and pushes the modulus in return. It has no other side effects.

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

This solution is largely based on @WheatWizard's previous 72-byte record, but it saves 6 bytes by never switching stacks.

Try it online!

How it works

             INPUT: a (dividend), b (divisor)
             INITIAL STACK: n = a, b

(
  {}         Pop and yield n = a.
  (<()>)       Push d = 0.
)              Push n + 0 = n.
             STACK: n, d = 0, b
{(           While n in non-zero:
  {}           Pop and yield n.
  [()]         Yield -1.
  <
   ((
     {}         Pop and yield d.
     ()         Yield 1.
     [({})]     Pop b, push it back on the stack, and yield -b.
   ))         Push d + 1 + -b = d + 1 - b twice.
   {          While/if d + 1 - b is non-zero, i.e., if d < b - 1
     {}         Pop d + 1 - b (second copy).
     (<(
       {}         Pop d + 1 - b (first copy).
       ({})       Pop b and push it back on the stack.
     )>)        Push d + 1 - b + b = d + 1, then 0.
   }          If the loop wasn't skipped entirely, pushing 0 breaks out.
              If d < b - 1, it essentially performs the assignment d = d + 1.
              However, if d = b - 1, we get d = d + 1 - b = b - 1 + 1 - b = 0.
              In all cases, we wind up with d = (d + 1) % b.
   {}         Pop 0.
  >         Yield 0.
)}        Push n + -1 + 0 = n - 1. Break if n - 1 = 0.
          STACK: n = 0, d = a % b, b
(
  {}        Pop and yield n = 0.
  {}        Pop and d = a % b.
  <{}>      Pop b, but yield 0.
)         Push 0 + a % b + 0 = a % b.
\$\endgroup\$
20
\$\begingroup\$

x86_32 machine code, 8 bytes

08048550 <div7>:
 8048550:   99                      cdq   
 8048551:   f7 f9                   idiv   %ecx
 8048553:   85 d2                   test   %edx,%edx
 8048555:   0f 94 c0                sete   %al

This is my first code golf answer, so hopefully I'm following all the rules.

This first calls cdq to clear out the edx register, then performs signed division on the ecx register, which stores the remainder in edx. The test edx, edx line will set the zero flag if edx is zero, and sete puts a 0 for false if edx was not zero, and puts a 1 for true if edx was 0.

This is just the code snippet that contributes to the byte count, but for testing, here is the C code I wrote with the inline assembly because it's easier this way to handle I/O.

\$\endgroup\$
  • 2
    \$\begingroup\$ Welcome to PPCG, nice first answer! \$\endgroup\$ – Leaky Nun Jul 23 '16 at 7:07
  • \$\begingroup\$ Does it need to be a full program? I was formatting my response kinda off this answer. And thank you! I'm hoping to get better at assembly/machine code for more code golfing! \$\endgroup\$ – davey Jul 23 '16 at 7:11
  • 1
    \$\begingroup\$ Input and output in specified registers in assembly is allowed by default: input, output. This is a perfectly acceptable submission. Welcome to PPCG! \$\endgroup\$ – Mego Jul 23 '16 at 7:31
  • \$\begingroup\$ Fantastic! Thank you! \$\endgroup\$ – davey Jul 23 '16 at 7:53
17
\$\begingroup\$

Hexagony, 15, 13, 12 10 bytes

Everybody's favorite hexagon-based language! :D

TL;DR works using magic, unformatted solutions in decreasing byte count:

?{?..>1'%<.@!'/
?{?!1\.'%<@.>
?{?\!1@'%\!(
?{?!1\@'%<

Saved 2 bytes thanks to @MartinEnder's layout wizardry.

@FryAmTheEggman saved 1 byte by using the corners more creatively

Both @MartinEnder and @FryAmTheEggman came up with a 10 byte solution that doesn't print anything for falsely values.

My solution (15):

Unformatted:

?{?..>1'%<.@!'/

Formatted:

  ? { ?
 . . > 1
' % < . @
 ! ' / .
  . . .

@Martin Ender's Solution (13):

Unformatted:

?{?!1\.'%<@.>

Formatted:

  ? { ?
 ! 1 \ .
' % < @ .
 > . . .
  . . .

Explanation:

First, we get the input and take the modulus.

  ? { ?
 . . . .
' % . . .
 . . . .
  . . .

Then, it checks if the modulus is 0 or not. If it is, the IP turns 60 degrees left, bounces off the mirror, sets the cell to 1 and prints.

Then, the IP continues onto the fourth row. When it reaches the >, it turns to the right instead (because the value of the cell is now 1). It goes oob, and comes back in the bottom right corner heading NW. The IP hits the <, goes along the top row, and comes back in the right corner to hit the @, stopping the program.

  . . .
 ! 1 \ .
. . < @ .
 > . . .
  . . .

If the modulus turns out to be positive, the IP turns 60 degrees to the right. Once it goes out the bottom right corner, it continues on the bottom left edge because of Hexagony's wrapping rules. The ' is reused to make the IP go to a cell with 0 in it. The IP then travels along the fourth row, wraps around to the second, hits print, and gets reflected into the <. The rest of the path to the @ is the same.

  . . .
 ! . \ .
' . < @ .
 > . . .
  . . .

That's some serious wizardry.

@FryAmTheEggman's Solution (12):

Unformatted:

?{?\!1@'%\!(

Formatted:

  ? { ?
 \ ! 1 @
' % \ ! (
 . . . .
  . . .

Explanation:

Like the other solutions, it gets the input and takes the modulus.

  ? { ?
 . . . .
' % . . .
 . . . .
  . . .

Then, the IP gets deflected into the bottom corner. If the modulus is positive, it goes on the top left edge. The ? has no more input, so it sets the cell to 0. The ! then prints the 0, and the @ terminates the program.

  ? . .
 \ ! . @
. . \ . .
 . . . .
  . . .

Things are much trickier for when the modulus is 0. First of all, it gets decremented, then reset to 0, then set to 1, then printed. Then, the 1 gets decremented to 0. After that, the program runs like it does at the beginning until it tries to do 0%0. That makes it throw a silent error and quit.

  ? { ?
 . . 1 .
' % \ ! (
 . . . .
  . . .

I really like the silent error trick, but a simpler way would be to replace the ( with / so that the IP passes through the first time, but gets reflected into @ the second.

Collaborative solution (10):

Unformatted:

?{?!1\@'%<

Formatted:

  ? { ?
 ! 1 \ @
' % < . .
 . . . .
  . . .

This program starts out the same as all the other programs, getting the input and modding it.

If the input is 0, the IP turns left when it hits <. It gets deflected into 1!@, which prints 1 and quits.

  . . .
 ! 1 \ @
. . < . .
 . . . .
  . . .

If the input is positive, the IP turns right when it hits <. It exits through the corner, and goes along the top right edge hitting the @ without printing.

  . . ?
 . . . @
. . < . .
 . . . .
  . . .
\$\endgroup\$
  • 6
    \$\begingroup\$ I think you should format your answer differently. Having four answers in a single code block makes it appear as if your byte count is wrong. \$\endgroup\$ – mbomb007 Oct 5 '16 at 20:00
17
\$\begingroup\$

Brain-flak 102, 98, 96 bytes

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

Eww. Gross. I might post an explanation, but I barely understand it myself. This language hurts my brain.

Try it online!

Thanks to github user @Wheatwizard for coming up with a modulus example. I probably could not have figured that out myself!

Also, the shorter answer is here.

Possibly incorrect explanation:

(({}<>))                    #Push this element onto the other stack
<>                          #Move back to stack one.
{                           #While the top element is non-zero:
 ({}[()])                   #  Decrement the number on top
 <>                         #  Move to the other stack
 (({}[()]))                 #  Push the top element minus one twice
 {                          #  While the top element is non-zero:
  {}                        #    Pop the top element
  (<          >)            #    Push a zero
        ({})                #    Push the second from top element
       [    ]               #    Evalue this second from top element as negative
    ({}      )              #    And push that negative plus the top element
 }
 {}                         #  Pop the top element
 ({}({}))                   #  Push the top element plus the second from the top, AND push the second from top
 <>                         #  Switch stacks
}

{}                          #Pop the stack
<>                          #Switch to the other stack
([{}]{})                    #And push the top element minus the second element.

The rest is pretty straightforward.

{              }            #While the top element is non-zero:
 <>                         #Move to the other stack
   (([()])  )               #Push a negative one
          ()                #AND push the previously pushed value + 1 (e.g. 0)

                 (      )   #Push:
                  {}{}      #The top two elements added together
                      ()    #Plus one
\$\endgroup\$
  • \$\begingroup\$ The rest is pretty straightforward. Yeah, it seems like it. \$\endgroup\$ – Erik the Outgolfer Oct 10 '16 at 15:57
  • \$\begingroup\$ 24 bytes if you count each brainflak instruction as a byte. \$\endgroup\$ – noɥʇʎԀʎzɐɹƆ Nov 8 '16 at 12:09
12
\$\begingroup\$

Javascript (ES6) 17 12 11 bytes

a=>b=>a%b<1
  • EDIT: Removed 5 bytes because 'a>0' is expected.
  • EDIT2: Removed 1 byte thanks to Downgoat.
\$\endgroup\$
  • \$\begingroup\$ Use currying to save one byte: a=>b=> \$\endgroup\$ – Downgoat Jul 21 '16 at 16:48
  • \$\begingroup\$ So how do I execute this? When I try d=a=>b=>a%b<1 followed by d(32,2) in the JS console... I simply get the response function b=>a%b<1 \$\endgroup\$ – WallyWest Oct 4 '16 at 2:05
  • \$\begingroup\$ @WallyWest this uses currying, so you would type in d(32)(2). Because d(32) gives function b=>a%b<1, you then have to call that function with your b value \$\endgroup\$ – Cyoce Oct 4 '16 at 4:21
9
\$\begingroup\$

Vim, 11 keystrokes

C<C-r>=<C-r>"<C-Left>%<C-Right><1<cr>

Not bad for a language that only handles strings. :D

\$\endgroup\$
  • \$\begingroup\$ What does <C-Left> do? Can't test it because it switches windows on mac >_> \$\endgroup\$ – Downgoat Jul 31 '16 at 17:04
  • 1
    \$\begingroup\$ @Downgoat are you using ctrl or command? Either way, it's equivalent to "b", except that it works in insert mode too. \$\endgroup\$ – DJMcMayhem Jul 31 '16 at 17:07
  • \$\begingroup\$ To be pedantic, it's the equivalent to B rather than b (and Ctrl+Right is the equivalent of W) - the difference is with non-word characters, but in this case it's doing the exact same thing :) vimdoc.sourceforge.net/htmldoc/motion.html#<C-Left> \$\endgroup\$ – Christian Rondeau Oct 5 '16 at 3:43
9
\$\begingroup\$

Mathematica - 17 13 3 bytes

Thanks to @MartinEnder for saving a ton of bytes!

\$\endgroup\$
  • \$\begingroup\$ What character is that? \$\endgroup\$ – Cyoce Oct 4 '16 at 4:38
  • \$\begingroup\$ @Cyoce I don't know its Unicode-code (on the phone at the moment), but it's an short operator for Divisible[]. \$\endgroup\$ – Yytsi Oct 4 '16 at 4:56
  • \$\begingroup\$ @Cyoce I think it's the pipe symbol, also known as shift+backslash. \$\endgroup\$ – Pavel Oct 7 '16 at 17:08
  • \$\begingroup\$ @Pavel if it were the pipe symbol, it would not be three bytes. \$\endgroup\$ – Cyoce Oct 7 '16 at 18:02
  • \$\begingroup\$ @Cyoce it's the U+2223 character: fileformat.info/info/unicode/char/2223/index.htm \$\endgroup\$ – numbermaniac Feb 15 '17 at 6:39
8
\$\begingroup\$

Retina, 12 bytes

^(1+)\1* \1$

Takes space-separated input in unary, like 111111111111 1111 to check if 12 if divisible by 4. Prints 1 (true) or 0 (false).

Try it online!

FryAmTheEggman saved two bytes. Oops, rewrote my answer to take the arguments in the right order. (Then Fry beat me to it in the comments. I’m slow at regex!)

\$\endgroup\$
  • \$\begingroup\$ To fix the order, if it becomes necessary, I think ^(1+)\1* \1$ will work. \$\endgroup\$ – FryAmTheEggman Jul 21 '16 at 16:53
  • \$\begingroup\$ I guess with the new spec, the opposite input order is fine again. \$\endgroup\$ – Martin Ender Jul 21 '16 at 19:56
8
\$\begingroup\$

Batch, 20 bytes

@cmd/cset/a!(%1%%%2)

Outputs 1 on success, 0 on failure.

\$\endgroup\$
8
\$\begingroup\$

C#, 27 13 12 Bytes

a=>b=>a%b<1;

Thanks to TuukkaX for pointing out anonymous lambdas are acceptable. Thanks to David Conrad for pointing me on to currying which I wasn't even aware was a thing.

Short and sweet, since we're only dealing with integers we can use <1 rather than ==0 and save a whole byte.

\$\endgroup\$
  • \$\begingroup\$ I'm not sure, but I think that you can just use a lambda: (a,b)=>a%b<1;. +1. \$\endgroup\$ – Yytsi Jul 22 '16 at 11:38
  • \$\begingroup\$ @TuukkaX, thanks I wasn't sure, it just seems so cheaty. \$\endgroup\$ – JustinM - Reinstate Monica Jul 22 '16 at 11:49
  • \$\begingroup\$ The JS version of this used currying to reduce it by one byte, and that should work for C#, too: a=>b=>a%b<1; (note: you then must call it as f(a)(b) rather than f(a,b)) \$\endgroup\$ – David Conrad Jul 22 '16 at 18:32
  • 1
    \$\begingroup\$ @DavidConrad oo that's neat, thank you. \$\endgroup\$ – JustinM - Reinstate Monica Jul 22 '16 at 20:18
7
\$\begingroup\$

brainfuck, 53 bytes

Takes input as bytes, output is a byte value of 0x00 or 0x01. It's the DivMod algorithm followed by Boolean negation.

,>,<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>,>[<+>,]+<[>-<-]>.

Try it online - Has a bunch of extra + near the end so you can see the output in ASCII.

\$\endgroup\$
  • \$\begingroup\$ Could you remove the "div" part of the thing to save bytes? \$\endgroup\$ – Leaky Nun Jul 22 '16 at 12:28
  • 1
    \$\begingroup\$ @LeakyNun This is the shortest known algorithm that gives the modulus. Removing part of it actually makes it longer, because you need more temporary cells. You cannot find a modulus without dividing. \$\endgroup\$ – mbomb007 Jul 22 '16 at 13:25
  • \$\begingroup\$ I see, thanks . \$\endgroup\$ – Leaky Nun Jul 22 '16 at 13:25
  • \$\begingroup\$ @LeakyNun Just look at how long the Division algorithm is. \$\endgroup\$ – mbomb007 Jul 22 '16 at 13:26
  • \$\begingroup\$ There are probably shorter ones, but if so, nobody has found or posted them. \$\endgroup\$ – mbomb007 Jul 22 '16 at 13:26
7
\$\begingroup\$

Brain-Flak, 88 86 bytes

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

This is a denser version of the original Brain-Flak divisibility test algorithm written by Dr Green Eggs and Iron Man DJMcMayhem and myself.

Here is a brief(ish) explanation of how it works:

  ({}<>)        #Move the top of the stack to the other stack #Start Mod
(<      >)      #Push zero
<>              #Switch stacks
{               #While the top of the stack is not zero
 ({}[()])       #Subtract one from the top of the stack
 <>             #Switch stacks
   {}()         #Pop the top, add one and ...
       [({})]   #Subtract the second element on the stack
 ((          )) #Push twice
 {              #If the top is not zero
  {}            #Pop the duplicate
    ({}({}))    #Add the second element to the first
  (<        >)  #Push zero
 }              #End if
 {}             #Pop the zero
 <>             #Switch back
}               #End While
<>              #Switch to the other stack
 ({}<{}>)       #Remove the second value on the stack         #End Mod
(        )      #Duplicate the result of modulation
{               #If the top is not zero
 {}{}           #Pop the top two elements
 (<(())>)       #Push a one and a zero
}               #End if
{}              #Pop the zero

Try it Online!

\$\endgroup\$
  • \$\begingroup\$ Link to online interpreter? \$\endgroup\$ – Leaky Nun Jul 25 '16 at 20:25
  • \$\begingroup\$ Nice work! Also welcome to the site! I hope you have fun here. (I certainly have) \$\endgroup\$ – DJMcMayhem Jul 25 '16 at 20:57
  • \$\begingroup\$ Nice first answer, welcome to PPCG! \$\endgroup\$ – Leaky Nun Jul 28 '16 at 2:49
6
\$\begingroup\$

LOLCODE, 74 64 bytes

HOW IZ I f YR a AN YR b
BOTH SAEM MOD OF a AN b AN 0
IF U SAY SO
\$\endgroup\$
  • \$\begingroup\$ It is a full program, current implementations do not require HAI and KTHXBYE \$\endgroup\$ – OldBunny2800 Jul 22 '16 at 15:50
  • \$\begingroup\$ OK, I'll try. One sec… \$\endgroup\$ – OldBunny2800 Jul 22 '16 at 15:59
  • \$\begingroup\$ No, it's two bytes longer. \$\endgroup\$ – OldBunny2800 Jul 22 '16 at 16:01
  • \$\begingroup\$ O RLY? I didn't know that! changing. \$\endgroup\$ – OldBunny2800 Jul 22 '16 at 16:09
  • \$\begingroup\$ BTW here is golfing tips. \$\endgroup\$ – Leaky Nun Jul 22 '16 at 16:11
6
\$\begingroup\$

C, 60 Bytes

#include <stdio.h>
main(){int a,b;scanf("%d %d",&a,&b);a%b==0;}
\$\endgroup\$
  • 1
    \$\begingroup\$ Why -1? Explain me \$\endgroup\$ – Ronronner Jul 21 '16 at 22:06
  • 3
    \$\begingroup\$ It's possible that nobody downvoted. This is a short answer so it got auto-flagged as low-quality, and then you edited it. For some reason, this casts an automatic downvote. Sorry about that. +1 from me. Also, we allow functions, so you could easily shorten this to int f(a,b){return !(a%b);} or possible even shorter. \$\endgroup\$ – DJMcMayhem Jul 21 '16 at 22:15
  • 3
    \$\begingroup\$ No, my point is that it does not have to be a full program. You may submit just a function instead. int f(a,b){return!(a%b);} is 25 bytes, and if you use the right compiler you could even do f(a,b){return!(a%b);} for 21 bytes. \$\endgroup\$ – DJMcMayhem Jul 21 '16 at 22:21
  • 3
    \$\begingroup\$ Even shorter function submission: #define f(a,b)!(a%b) (ideone link) \$\endgroup\$ – Mego Jul 21 '16 at 23:17
  • 2
    \$\begingroup\$ You need to define a function or a program, not just a snippet. \$\endgroup\$ – Leaky Nun Jul 22 '16 at 11:07
5
\$\begingroup\$

Dyalog APL, 3 bytes

0=|

Is zero equal to the division remainder?

\$\endgroup\$
  • 3
    \$\begingroup\$ This works in J too. \$\endgroup\$ – miles Jul 21 '16 at 16:34
5
\$\begingroup\$

R, 22 20 bytes

a=scan();!a[1]%%a[2]

As usually, reads two numbers from the input that is terminated by an empty line.

Update: thanks to Jarko Dubbeldam for shaving off 2 bytes (despite the fact that his edit was rejected, it was very helpful!).

\$\endgroup\$
5
\$\begingroup\$

Java 8, 11 bytes

a->b->a%b<1

What the heck, there are JS and C# versions of this, why not a Java version, too?

Usage:

import java.util.function.Function;

public class Program {
    public static void main(String[] args) {
        System.out.printf("%d, %d %b%n", 9, 3, divides(9, 3, a->b->a%b<1));
        System.out.printf("%d, %d %b%n", 3, 9, divides(3, 9, a->b->a%b<1));
    }

    public static boolean divides(int a, int b,
            Function<Integer, Function<Integer, Boolean>> f) {
        return f.apply(a).apply(b);
    }
}
\$\endgroup\$
  • \$\begingroup\$ a->b->a%b<1 This raises a syntax error, doesn't it? \$\endgroup\$ – dorukayhan wants Monica back Jul 23 '16 at 16:17
  • 2
    \$\begingroup\$ No, it's valid Java 8. \$\endgroup\$ – David Conrad Jul 23 '16 at 21:25
  • \$\begingroup\$ Sometimes even Java is looking like Perl... \$\endgroup\$ – Mega Man Jul 27 '16 at 17:06
  • \$\begingroup\$ Yeah, I'd add in that this is Java 8 only ;). \$\endgroup\$ – Magic Octopus Urn Sep 13 '16 at 20:23
  • \$\begingroup\$ so with Java 8 we have to count only lambda expression bytes not the whole class and function boilerplate, cool ! \$\endgroup\$ – Sikorski Oct 3 '16 at 6:43
4
\$\begingroup\$

Python, 16 bytes

lambda D,d:D%d<1
\$\endgroup\$
  • 1
    \$\begingroup\$ Note that this wouldn't work if negative integers were allowed. Luckily, the inputs are strictly positive. \$\endgroup\$ – TLW Jul 24 '16 at 0:46
  • \$\begingroup\$ I did lambda a,b:1.*a/b==a/b, but was quite impressed. This is a so complex piece of code... \$\endgroup\$ – Erik the Outgolfer Oct 3 '16 at 10:53
4
\$\begingroup\$

GolfScript, 3 bytes

~%!

Explanation:

~    # Evaluate the input
 %   # Take the first modulus the second
  !  # Boolean not

Try it online!

\$\endgroup\$
4
\$\begingroup\$

CJam, 6 4 bytes

Saved 2 bytes thanks to Dennis

q~%!

Try it online

q    e# Take in the input
 ~   e# Dump the individual values to the stack
  %  e# Modulus
   ! e# Boolean NOT
\$\endgroup\$
4
\$\begingroup\$

Brachylog, 2 bytes

%0

Try it online!

\$\endgroup\$
3
\$\begingroup\$

Julia, 9 bytes

D\d=D%d<1

Try it online!

\$\endgroup\$
3
\$\begingroup\$

Fortran 95, 78 bytes

function f(i,j)result(k)
integer::i,j,k
k=merge(1,0,MOD(i,j)<1)
end function f
\$\endgroup\$
3
\$\begingroup\$

MarioLANG, 121 109 107 bytes

Saved 14 bytes thanks to Martin Ender

;>(-)-)+(([!)
)"=========#[
; +(![-)< )<!+
  ==#==="  "#:
>!< >(+ !![(<
=#"="===##=:"
  !      <
  #======"

Try it online!

Explanation

The algorithm is simply to keep subtracting d from n to see if you can do it an integer number of times and have no remainder.

;
)
;

>
=
 
 

First, the input is collected. n is in the first cell, d in the second.

 >(-)-)+(([!
 "=========#
          )<
           "
 !
 #"="===##=
  
  

This is essentially the main loop. It decrements the first and second cells, and increments the third.

           [!)
           =#[
             !+
             #:
            (<
            :"
 
 

This is the final output. If after the incrementing/decrementing, the first cell is 0, then we've eliminated n. If after this, the second cell (d) is 0, then d went into n evenly. We increment and print (1). Otherwise, move back to the first cell (which is 0) and print it.

 
 
  +(![-)<  
  ==#==="  
 !< >(+ !![
 #"="===##=
  !      <
  #======"

This loop happens if the second cell is 0 after incrementing and decrementing. It copies the third cell to the second cell. The part at the bottom is to bypass the loop if the cell is not 0.

\$\endgroup\$
3
\$\begingroup\$

Tcl , 34 bytes

ge stdin a
ge stdin b
exp $a%$b<1

My first /*successful*/ attempt in codegolf ! This code must be executed in Tcl shell , otherwise it will not work.

One byte thanks to @Lynn .

Four bytes thanks to @Lynn and @LeakyNun (now I understand what he meant)!

\$\endgroup\$
  • \$\begingroup\$ Can you omit ?1:0? \$\endgroup\$ – Leaky Nun Jul 21 '16 at 16:33
  • \$\begingroup\$ @LeakyNun it's ternary operation . you mean just to return sth when it's devisible ? \$\endgroup\$ – user55673 Jul 21 '16 at 16:34
  • \$\begingroup\$ What would $a%$b==0 return? \$\endgroup\$ – Leaky Nun Jul 21 '16 at 16:36
  • 1
    \$\begingroup\$ I mean, can your third line just be exp $a%$b==0? \$\endgroup\$ – Leaky Nun Jul 21 '16 at 16:42
  • 1
    \$\begingroup\$ Or exp $a%$b<1, maybe? \$\endgroup\$ – Lynn Jul 21 '16 at 16:57
3
\$\begingroup\$

PHP, 23 22 bytes

<?=$argv[1]%$argv[2]<1

prints 1 for true, empty string (=nothing) for false

call from cli with n and d as arguments


10 bytes for ancient PHP: <?=$n%$d<1

\$\endgroup\$
  • \$\begingroup\$ If you don't mind using PHP4.1: <?=!($A%$B). The values can be passed as part of your $_SESSION, $_COOKIE, $_POST, $_GET or (if I'm not mistaken) over $_ENV. \$\endgroup\$ – Ismael Miguel Jul 22 '16 at 17:38
  • \$\begingroup\$ @Ismael Miguel: Actually I don´t, but I am tired of posting for ancient PHP versions and adding for PHP<5.4 with register_globals=On. But I´ll add it for reference. \$\endgroup\$ – Titus Jul 22 '16 at 17:57
  • \$\begingroup\$ Actually, you can't say "for PHP<5.4 with register_globals=On", since you have to count the bytes of your php.ini file containing register_globals=On. However, PHP4.1 is a special case. It is the last version where register_globals=On is the default value, and most functions are available from PHP4.1 and up. This version also allows the use of other functions, like ereg and split without warnings. \$\endgroup\$ – Ismael Miguel Jul 22 '16 at 19:07
3
\$\begingroup\$

J, 3 bytes

0=|

Usage:

2 (0=|) 10 

Will return 1. And is equivalent to pseudocode 10 MOD 2 EQ 0

Note this is very similar to the APL answer, because J is heaviliy inspired by APL

\$\endgroup\$
  • \$\begingroup\$ Nice first answer, welcome to PPCG! \$\endgroup\$ – Leaky Nun Jul 23 '16 at 23:17
  • \$\begingroup\$ @LeakyNun Thanks, I've always browsed around, nice to finally answer. \$\endgroup\$ – emiflake Jul 24 '16 at 8:54
3
\$\begingroup\$

PowerShell v2+, 20 bytes

!($args-join'%'|iex)

Takes input as two command-line arguments $args, -joins them together into a string with % as the separator, pipes that to iex (short for Invoke-Expression and similar to eval). The result is either 0 or non-zero, so we take the Boolean not ! of that result, which means either $TRUE or $FALSE (non-zero integers in PowerShell are truthy). That Boolean is left on the pipeline and output is implicit.

Alternative versions, also 20 bytes each

param($a,$b)!($a%$b)
!($args[0]%$args[1])

Same concept, just slightly different ways of structuring the input. Thanks to @DarthTwon for providing these.

Examples

PS C:\Tools\Scripts\golfing> .\divisibility-test.ps1 24 12
True

PS C:\Tools\Scripts\golfing> .\divisibility-test.ps1 24 13
False

PS C:\Tools\Scripts\golfing> .\divisibility-test.ps1 12 24
False
\$\endgroup\$
  • \$\begingroup\$ In both of the other methods I tried golfing this question, I got them to 20 bytes also: param($a,$b)!($a%$b) and !($args[0]%$args[1]) \$\endgroup\$ – ThePoShWolf Jul 26 '16 at 14:48
  • \$\begingroup\$ @DarthTwon Indeed. When dealing with small amounts of operations, there's usually at most one or two bytes differences in the different ways of taking the input arguments. \$\endgroup\$ – AdmBorkBork Jul 26 '16 at 15:01
  • \$\begingroup\$ I was hoping to come up with something shorter :P but yeah, there's always multiple ways to skin the cat, especially in PS. \$\endgroup\$ – ThePoShWolf Jul 26 '16 at 15:10
3
\$\begingroup\$

Haskell, 13 11 bytes

((1>).).mod

This defines a new function (!) :: Integral n => n -> n -> Bool. Since mod n m returns only positive numbers if n and m are positive, we can save a byte by using 1> instead of 0==.

Usage:

ghci> let n!d=1>mod n d
ghci> 100 ! 2
True
ghci> 100 ! 3
False
\$\endgroup\$
  • \$\begingroup\$ You can go pointfree and save 2 bytes: ((1>).).mod. \$\endgroup\$ – nimi Aug 5 '16 at 20:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.