Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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>

share|improve this question
    
This conversation has been moved to chat. – Dennis 22 hours ago

47 Answers 47

Jelly, 1 byte:

This took me hours to golf.

Try it online!

share|improve this answer
    
wow that's very very complex! – Matthew Roh 5 hours ago
    
That's two bytes, not one. The "ḍ" character is a Unicode character that takes up two bytes. – Runemoro 3 hours ago
2  
@Runemoro Jelly has it's own encoding. On Jelly's code-page you can find all 256 used. – Kevin Cruijssen 3 hours ago

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!

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
share|improve this answer

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
share|improve this answer

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

share|improve this answer
    
To fix the order, if it becomes necessary, I think ^(1+)\1* \1$ will work. – FryAmTheEggman yesterday
    
I guess with the new spec, the opposite input order is fine again. – Martin Ender 21 hours ago

Vim, 11 keystrokes

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

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

share|improve this answer

Hexagony, 15, 13, 12 10 bytes

Everybody's favorite hexagon-based language! :D

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:

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.

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.

  . . ?
 . . . @
. . < . .
 . . . .
  . . .
share|improve this answer
    
I don't think 00 should count as falsy, because Hexagony has no way of representing it. But this is tantalizingly close to working, so maybe you'll be able to see something I haven't. – FryAmTheEggman 4 hours ago
    
Well, I got a slightly less exciting version that's 1 byte shorter: hexagony.tryitonline.net/… – FryAmTheEggman 3 hours ago
    
Assuming no output is falsy, the best Martin and I could come up with is: hexagony.tryitonline.net/… – FryAmTheEggman 3 hours ago

Dyalog APL, 3 bytes

0=|

Is zero equal to the division remainder?

share|improve this answer
    
This works in J too. – miles yesterday

GolfScript, 3 bytes

~%!

Explanation:

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

Try it online!

share|improve this answer
8  
@LeakyNun It's a different language? – Dennis yesterday

Batch, 20 bytes

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

Outputs 1 on success, 0 on failure.

share|improve this answer

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.

share|improve this answer
    
Could you remove the "div" part of the thing to save bytes? – Leaky Nun 5 hours ago
    
@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. – mbomb007 4 hours ago
    
I see, thanks . – Leaky Nun 4 hours ago
    
@LeakyNun Just look at how long the Division algorithm is. – mbomb007 4 hours ago
    
There are probably shorter ones, but if so, nobody has found or posted them. – mbomb007 4 hours ago

Python, 16 bytes

lambda D,d:D%d<1
share|improve this answer
    
Might be missing something, but why is it <1 instead of =0? Is it due to precision errors? – Mar Dev 29 secs ago

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.
share|improve this answer
    
Use currying to save one byte: a=>b=> – Downgoat yesterday

Julia, 9 bytes

D\d=D%d<1

Try it online!

share|improve this answer

Actually, 3 2 bytes

%Y

Saved one byte thanks to @Mego.

Try it online!

share|improve this answer
    
%Y is shorter – Mego 18 hours ago

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
share|improve this answer
    
It is a full program, current implementations do not require HAI and KTHXBYE – OldBunny2800 2 hours ago
    
OK, I'll try. One sec… – OldBunny2800 1 hour ago
    
No, it's two bytes longer. – OldBunny2800 1 hour ago
    
O RLY? I didn't know that! changing. – OldBunny2800 1 hour ago
    
BTW here is golfing tips. – Leaky Nun 1 hour ago

Brachylog, 2 bytes

%0

Try it online!

share|improve this answer

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
share|improve this answer

MATL, 2 bytes

\~

Try it online!

\    % Take two inputs implicitly. Compute their modulo
~    % Logical negate. Implicit display
share|improve this answer

Befunge, 6 bytes

&&%!.@

Try it here! Input two numbers, separated by a space. Output is 0 or 1 for falsy or truthy.

share|improve this answer

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.

share|improve this answer

C, 60 Bytes

#include <stdio.h>
main(){int a,b;scanf("%d %d",&a,&b);a%b==0;}
share|improve this answer
1  
Why -1? Explain me – Ronronner 19 hours ago
2  
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. – Dr Green Eggs and Iron Man 19 hours ago
1  
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. – Dr Green Eggs and Iron Man 19 hours ago
2  
Even shorter function submission: #define f(a,b)!(a%b) (ideone link) – Mego 18 hours ago
2  
You need to define a function or a program, not just a snippet. – Leaky Nun 6 hours ago

Pyke, 2 bytes

%!

Try it here!

not (a mod b)
share|improve this answer

Minkolang 0.15, 6 bytes

nn%,N.

Try it here!

Explanation

nn        Take two numbers from input
  %       Pop b, a and push a%b
   ,      NOT top of stack
    N.    Output as number and stop.
share|improve this answer

Perl 5, 14 bytes

A subroutine:

{!((pop)%pop)}

See it in action thus:

perl -E"say sub{!((pop)%pop)}->(3,17)"

First argument is d, second is n.

share|improve this answer

Labyrinth, 8 bytes

??
@%
!1

Input is just the two numbers, using any non-numeric separator of your choice. Output is either 1 for truthy or nothing at all for falsy.

Try it online!

Explanation

There's only one branch in the execution and that's after the modulo (%). When the input is a truthy case, the following is executed:

?   Read integer and push onto stack.
?   Read integer and push onto stack.
%   Take the first modulo the second integer. The result is zero, so the
    instruction pointer keeps moving south.
1   Turn that zero into a one.
!   Print it.
@   Terminate the program.

Otherwise, the following code is executed:

?   Read integer and push onto stack.
?   Read integer and push onto stack.
%   Take the first modulo the second integer. The result is positive, so
    the instruction pointer turns west.
@   Terminate the program.
share|improve this answer

Racket, 26 bytes

(λ(n m)(integer?(/ n m)))
share|improve this answer

05AB1E, 6 bytes

II%0Q,

Uses CP-1252 encoding. Try it online!

You can also use the built in

Ö

which does exactly what the challenge asks. Just that the 2 inputs are swapped. Try it online!

share|improve this answer
    
Very nice! You can also use the built-in Ö which does exactly what the challenge asks. You only need to specify that the 2 inputs are swapped. – Adnan 19 hours ago

C#, 27 13 Bytes

(a,b)=>a%b<1;

Thanks to TuukkaX for pointing out anonymous lambdas are acceptable.

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

share|improve this answer
    
I'm not sure, but I think that you can just use a lambda: (a,b)=>a%b<1;. +1. – TuukkaX 6 hours ago
    
@TuukkaX, thanks I wasn't sure, it just seems so cheaty. – Phaeze 6 hours ago

Bash, 23 bytes

expr `expr $N % $D` % 2

I'm sure it can be even shorter...

Output is 0 if N is divisible by D, 1 if it is not

share|improve this answer
2  
Truthy and falsy don't mean literally the strings "truthy and "falsy", just whatever the natural true/false values are for the language. In the case of bash I'd say an exit code of 0 for truthy and an exit code of 1 for falsy would be appropriate here. – quartata 1 hour ago

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

share|improve this answer
    
Can you omit ?1:0? – Leaky Nun yesterday
    
@LeakyNun it's ternary operation . you mean just to return sth when it's devisible ? – GLASSIC yesterday
    
What would $a%$b==0 return? – Leaky Nun yesterday
1  
I mean, can your third line just be exp $a%$b==0? – Leaky Nun yesterday
1  
Or exp $a%$b<1, maybe? – Lynn yesterday

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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