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

1
\$\begingroup\$

Clojure, 15 bytes

#(=(mod % %2)0)
\$\endgroup\$
1
\$\begingroup\$

dc, 8 7 bytes

Input is delimited by a space: n d

?~/z1-n

If false, it outputs 0. If true, it outputs 1 and throws an error about division by zero.

Explanation:

?   # Take input from stdin.
~   # Pop two values from stack. Push quotient. Push remainder.
/   # Attempt to divide quotient by remainder.
    #   If input is divisible, then remainder is 0.
    #     Division fails, throwing an error and leaving both numbers on stack.
    #     (Stack depth is 2.)
    #   If input is not divisible, then remainder is not 0.
    #     Division succeeds, and result is pushed on stack. (Stack depth is 1.)
z   # Push stack depth on stack. (If divisible, push 2; if indivisible, push 1.)
1-  # Subtract 1 from top of stack. ToS is now 1 or 0.
n   # Pop top of stack and print it as a number.
\$\endgroup\$
  • \$\begingroup\$ Ironically, this reports that all numbers are divisible by 0. \$\endgroup\$ – Joe Jul 23 '16 at 0:42
  • \$\begingroup\$ I came back and re-read this answer and it totally confused me. "Why was I dividing the quotient? What was I thinking?" I just realized, it doesn't matter what the quotient is, or what the second quotient is. What matters is whether the division is possible—if the ~ gave remainder 0, then division is not possible again, which is what differentiates a true case from a false one. \$\endgroup\$ – Joe Oct 4 '16 at 6:47
1
\$\begingroup\$

Sesos, 16 bytes

Hexdump:

0000000: d6659c af71e7 a0fbf8 70cedc ae8de7 1e             .e..q....p......

Try it online!

Assembler:

set numin
set numout
get,fwd 1,get,rwd 1
jmp
  fwd 1,sub 1,fwd 1,add 1,rwd 1
  jmp
    fwd 2
  jnz
  fwd 1
  jmp
    sub 1,rwd 1,add 1,fwd 1
  jnz
  rwd 3
  jmp
    rwd 1
  jnz
  fwd 1
  sub 1
jnz
fwd 4,add 1,rwd 2
jmp
  fwd 1
jnz
fwd 2
put

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

\$\endgroup\$
1
\$\begingroup\$

ROOP, 24 bytes

I
w
 w
R #H
 #
N
 #
W
O#

The I is the input object. When the object is on the operator w wait the entry of a number that puts it under. Then the I moves to the right and falls on the second w waiting for the second number. The operator R removes those two numbers, and make the remainder of divide them below. The N operator removes that number and creates a 1 if the number was 0, and 0 otherwise. Then the W operator puts that number in the O object representing the output. At the same time the I reached the operator H that ends execution.

\$\endgroup\$
1
\$\begingroup\$

Batch, 27 bytes

for /l %a IN (1,1,10)DO @%a

Does ' is not recognized as an internal or external command, operable program or batch file.' count as a separator?

\$\endgroup\$
1
\$\begingroup\$

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!

Alternative solution that prints 0 for falsy but terminates with an error (same byte count):

<1%??
!;

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.
\$\endgroup\$
1
\$\begingroup\$

Java, 13 bytes

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

This is a java.util.function.BiPredicate<Integer, Integer>.

As something that makes more sense to those who are new to Java, it takes up 37 bytes:

boolean A(int b,int B){return b%B<1;}

As something that compiles, it takes up 46 bytes:

class a{boolean A(int b,int B){return b%B<1;}}

As something that runs, it takes up 104 bytes:

interface a{static void main(String[]A){System.out.print(Integer.decode(A[0])%Integer.decode(A[1])<1);}}

For the sake of completeness, here's a 50-byte lambda that checks if an arbitrarily large integer a is divisible by another arbitrarily large integer b. It's a BiPredicate<BigInteger, BigInteger>.

(a,b)->a.mod(b).equals(java.math.BigInteger.ZERO);
\$\endgroup\$
  • \$\begingroup\$ I'm quite sure that there's this exact answer somwhere here... \$\endgroup\$ – Leaky Nun Jul 23 '16 at 16:40
  • \$\begingroup\$ @LeakyNun Well, in fact this is semantically different than the answer you're looking for - David's answer nests two lambdas, while mine uses a single lambda with two parameters. They just exploit the identical rule which states that if a is divisible by b then a mod b is 0. \$\endgroup\$ – dorukayhan wants Monica back Jul 23 '16 at 16:48
1
\$\begingroup\$

Logicode, 289 262 bytes

Presenting the language that's more verbose than Java!

circ d(n)->cond n<->0+n/d(n>)
circ e(n)->[
cond n->var a=~((~(d(n)))>)/var a=0
cond (~n)<->var b=a+0/var b=e(a)+1
b
]
circ f(a,b)->cond *a&*b->f(e(a),e(b))/a
circ g(a,b)->!(*(f(b,a)))
circ h(a,b)->cond b->h(e(a),e(b))/a
circ i(a,b)->cond g(a,b)->i(h(a,b),b)/c(a)

I'll post an explanation later, but it's basically a shortened version of my prime checker.

Added a new feature: * (boolean)!

\$\endgroup\$
1
\$\begingroup\$

Vitsy, 1 Byte

This is a function that leaves 0 on the stack if true and a non-zero integer on the stack if false.

M

(This is the modulo function.)

Try it Online!

(N has been added for output).

\$\endgroup\$
  • \$\begingroup\$ Is 0 truthy in Vitsy? \$\endgroup\$ – Dennis Oct 5 '16 at 17:29
  • \$\begingroup\$ @Dennis: Technically -1 < x < 1 is truthy because of how I've set up the ( (if) command. \$\endgroup\$ – Addison Crump Oct 5 '16 at 17:30
  • \$\begingroup\$ Huh. A bit unconventional, but certainly interesting. \$\endgroup\$ – Dennis Oct 5 '16 at 17:33
1
\$\begingroup\$

Emotinomicon, 16

😼😼😌😨

Explanation:

😼😼😌😨 
😼        pushes integer input
  😼      pushes integer input
    😌    pops n,m; pushes n mod m
      😨  pops n; outputs as number

Returns zero for truthy if first integer is divisible by second, returns non-zero for falsy.

\$\endgroup\$
1
\$\begingroup\$

05AB1E, 2 1 byte

Ö

Try it online!

Was (Test here) but arguments switched (suggested by @Mego). This allowed me to golf down to 1 byte.

Explanation (old):

s    Reverses input e.g. 6, 3 -> 3,6 so that input is in correct order
 Ö   Checks if (top of stack % second top of stack) == 0 e.g. 6 % 3 == 0
     Implicitly prints (1 because 6 % 3 = 0)
\$\endgroup\$
  • \$\begingroup\$ Reversing the stack isn't necessary - you can just take the input in the opposite order. \$\endgroup\$ – Mego Oct 7 '16 at 17:24
  • \$\begingroup\$ Are you sure the inputs can be taken in that order according to the rules? If they can, I will switch to just Ö. @Mego \$\endgroup\$ – Geno Racklin Asher Oct 7 '16 at 18:38
1
\$\begingroup\$

Elixir, 14 bytes

&rem(&1,&2)==0

Anonymous function defined using the capture operator.

Full program with test cases (yes, the . in the function call is mandatory!):

s=&rem(&1,&2)==0
# test cases
IO.puts s.(1,1) # true
IO.puts s.(2,1) # true
IO.puts s.(6,3) # true
IO.puts s.(17,17)   # true
IO.puts s.(22,2)    # true
IO.puts s.(1,2) # false
IO.puts s.(2,3) # false
IO.puts s.(2,4) # false
IO.puts s.(3,9) # false
IO.puts s.(15,16)   # false

Try it online on ElixirPlayground !

\$\endgroup\$
1
\$\begingroup\$

Python 2, 24 bytes

print input()%input()==0
\$\endgroup\$
  • \$\begingroup\$ Only works with Python 2 not 3 \$\endgroup\$ – Kritixi Lithos Nov 20 '16 at 19:43
  • \$\begingroup\$ Sorry, I mistyped on the title, it was meant to say python 2 \$\endgroup\$ – sonrad10 Nov 20 '16 at 19:47
1
\$\begingroup\$

Groovy, 12 chars/bytes

Adding a Groovy version just for the sake of completeness, and for a comparison with the Java 8 snippet above.

Groovy is a Java-based language compiled to JVM bytecode, and was designed with a very concise syntax in mind, allowing less boilerplate code than pure Java. But if failed this time! The actual code is one byte shorter than Java, but needs the curly braces in order to compile as an anonymous closure, making it 1 byte longer at 12 bytes:

{n,d->n%d<1}

To run with n=9, d=3, just do this:

println ({n,d->n%d<1}(9,3))

You can try it online on http://groovyconsole.appspot.com

\$\endgroup\$
1
\$\begingroup\$

ASMD, 3 bytes (non-competing)

%0=
\$\endgroup\$
1
\$\begingroup\$

Keg, 4 bytes

¿¿%;

TIO

Takes 2 integers, modulos them. A zero value is falsy, and a non-zero value is truthy.

\$\endgroup\$
0
\$\begingroup\$

q - 9 bytes

An anonymous lambda, returns boolean true/false

not(mod).

Example

q)not(mod). 18 4
0b
q)not(mod). 18 3
1b
\$\endgroup\$
  • \$\begingroup\$ What is the use of .? \$\endgroup\$ – Leaky Nun Jul 23 '16 at 12:04
  • \$\begingroup\$ . applys a function, passing a list as the parameters (e.g. as opposed to writing f[18;3] you can write f . 18 3) \$\endgroup\$ – skeevey Jul 23 '16 at 13:47
0
\$\begingroup\$

3d, 15 bytes

>::%v
;!T'_'F!;

Takes 2 numbers a and b as input, proceed a mod b, prints T if result is 0, F else. Simple and efficient.
Can be golfable, but since I'm still working on the aforelinked interpreter, I might not come back on it for improvement.
I'm just making a little advertising for my esolang ;)

\$\endgroup\$
0
\$\begingroup\$

><>, 3 bytes

%n;

Input numbers are assumed to be on the stack. ><> does not have any default truthy or falsy values, so I use 0 as truthy and everything else as falsy. That seems to be allowed. (If not, 1-truthy, 0-falsy, can be done like this in 5 bytes: %0=n;).

\$\endgroup\$
  • 2
    \$\begingroup\$ ><> does have the conditional ?, so in this sense zero should be falsy and everything else should be truthy I think, since the next instruction is only executed if nonzero. Also, I'm not quite sure about assuming input is on the stack for full programs, but I can't seem to find a relevant meta post... (usually for ><> the -v flag is used for +3 bytes) \$\endgroup\$ – Sp3000 Jul 25 '16 at 11:00
  • \$\begingroup\$ @Sp3000 It takes some time getting used to what things you are allowed to exploit. A low byte count is almost impossible without. \$\endgroup\$ – Hohmannfan Jul 25 '16 at 11:21
  • \$\begingroup\$ In my opinion, since the questions asks for a program or function, I would allow getting parameters from the stack. However, if going that way, I would also have avoided the use of n and ; : once my function run, I would expect it to "return" to any other piece of code it would be included in, leaving its result on the stack. However, I agree that 0 in ><> is the boolean false, while every other number is a valid representation of the boolean true. Personally, I would have answered with %0= \$\endgroup\$ – Aaron Oct 4 '16 at 9:15
0
\$\begingroup\$

Magma, 13 bytes

IsDivisibleBy

Pretty readable, I think. Try it at the online calculator, e.g.

IsDivisibleBy(100, 50);
IsDivisibleBy(100, 54);

gives

true
false
\$\endgroup\$
0
\$\begingroup\$

MIXAL, 105 bytes

Not counting bytes for 17 and 8 in the first two lines, which are used for input. Replace with any desired n and d.

Outputs 0 for true and 1 for false.

N       EQU     17
D       EQU     8
S       LDX     =N=
        DIV     =D=
        ENTA    30
        JXZ     T
        INCA    1
T       STA     9
        OUT     9(19)
        HLT
        END     S

Commented version:

N       EQU     17      Constants used for input                                                                                                                                               
D       EQU     8
START   LDX     =N=     Put value 'n' into rX                                                                                                                                                  
        DIV     =D=     Divide rAX by value 'd'; rA <= quotient; rX <= remainder                                                                                                               
        ENTA    30      Replace rA value with character code for '0'                                                                                                                           
        JXZ     T       If rX == 0, then d is a divisor of n, go to 'T'                                                                                                                        
        INCA    1       Else (there is a remainder), add 1 to rA charcode for '1'                                                                                                              
T       STA     9       Store rA charcode at address 9 (after end of program)                                                                                                                  
        OUT     9(19)   Send contents starting at address 9 to TTY output device                                                                                                               
        HLT
        END     START
\$\endgroup\$
0
\$\begingroup\$

RProgN, 3 Bytes

% !

Explination

%   # Take the Modulus of the value under the top of the stack compared to the top of the stack. (The Inputs in order, conveniently enough)
!   # Push the Boolean not of it. In this case, 0 is falsey, and all numbers !=0 are truthy, so false correctly inverts it.

Yay, RProgN is a competitive language!

\$\endgroup\$
0
\$\begingroup\$

Perl 6, 4 bytes

*%%*

Anonymous function that takes 2 arguments, here represented with *, using the infix "is divisable by" operator %%, which returns a Bool value

\$\endgroup\$
0
\$\begingroup\$

PHP, 53 Bytes

Trying to get the boutny for an exemplary answer

$r=range($d=$argv[2],$n=$argv[1],$d);echo$n==end($r);

My answer based on Set Theory In the set from d to n where all items are multiple from d if n is the last member of the set it is divisible by d

Expressed differently you could say that the count of the items multiplied with d must be n

$r=range($d=$argv[2],$n=$argv[1],$d);echo$n==count($r)*$d;
\$\endgroup\$
0
\$\begingroup\$

Racket 26 bytes

(λ(n m)(= 0(modulo n m)))

Usage:

(define f
  (λ(n m)
    (= 0
       (modulo n m))))

Testing:

(f 1 1)
(f 2 1)
(f 6 3)
(f 17 17)
(f 22 2)
(f 1 2)
(f 2 3)
(f 2 4)
(f 3 9)
(f 15 16)

Output:

#t
#t
#t
#t
#t
#f
#f
#f
#f
#f
\$\endgroup\$
0
\$\begingroup\$

tinylisp (REPL), 38 bytes

(d |(q((N D)(i(l N D)(e N 0)(|(s N D)D

Defines a function | that takes N and D and returns 1 if divisible, 0 otherwise. The REPL infers closing parentheses as necessary at the end of the code. Call the function like (| 22 2).

Ungolfed/explanation:

(d |                  Define | to be...
 (q (                 a function, i.e. a list containing...
  (N D)               list of params N and D, and function body:
  (i (l N D)           If N is less than D, then return:
   (e N 0)              1 if N equals 0, 0 otherwise;
   (| (s N D) D)))))    Else, recurse with arguments N - D and D

Gets kinda slow for N around D * 10^5 and larger.

\$\endgroup\$
0
\$\begingroup\$

TI-Basic, 10 bytes

Prompt N,D:not(fPart(N,D

Returns 1 for true or 0 for false

\$\endgroup\$
0
\$\begingroup\$

GameMaker Language, 32 bytes

return 1>argument0 mod argument1
\$\endgroup\$
0
\$\begingroup\$

bc, 19 bytes

!read()%read()
quit

The positive integers n and d are read from STDIN in that order, separated by any whitespace. The script prints 1 if n is evenly divisible by d, or 0 otherwise.

Run examples:

me@LCARS:/PPCG$ bc --quiet divisibility_test.bc
12 4
1
me@LCARS:/PPCG$ bc --quiet divisibility_test.bc
12 5
0
\$\endgroup\$
0
\$\begingroup\$

AWK, 14 bytes

{$0=!($1%$2)}1

Usage:

awk '{$0=!($1%$2)}1' <<< "N D"

Output will be 1 for true and 0 for false. N and D can be integers or floating point numbers.

\$\endgroup\$

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.