38
\$\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

101 Answers 101

1 2 3
4
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.

|improve this answer|||||
\$\endgroup\$
0
\$\begingroup\$

QBIC (Non-competing), 8 bytes

::?a%b=0

For this challenge, I've improved QBIC's user input of numeric values. : now takes a command line argument and casts this to num.

|improve this answer|||||
\$\endgroup\$
0
\$\begingroup\$

Excel VBA, 14 Bytes

Anonymous VBE immediates window function that takes input of expected type variant\integer from cells [A1] and [A2] and outputs as a boolean variable to the VBE immedates window

?[A1]mod[A2]=0
|improve this answer|||||
\$\endgroup\$
0
\$\begingroup\$

REXX, 18 bytes

arg n d
say n//d=0
|improve this answer|||||
\$\endgroup\$
0
\$\begingroup\$

Functoid, 21 bytes

Y(yg(KZ)(BBC+C-))$$;@

Full program expecting two arguments d and n, try it online!

Explanation

Y(              )      # fix point of the following function
  y                    # define recursive function with 2 arguments
   g                   #   - base case: x > y
    (KZ)               #   - in base case: check y == 0
        (BBC+C-)       #   - else: call f recursively with x and (y-x)
                 $$    # apply two command-line arguments
                   ;   # print as a boolean 
                    @  # terminate program
|improve this answer|||||
\$\endgroup\$
0
\$\begingroup\$

T-SQL, 27 bytes

Per our input standards, input is provided via pre-existing table t, with integer fields n and d:

SELECT IIF(n%d=0,1,0)FROM t

'%' is the remainder/modulo operator in SQL.

Note that the original list of test values could be improved: the 5 failing cases all fail trivially because n < d. Some better test values (5 succeeding, 5 failing):

(200,50),(91,7),(999,3),(45,5),(10000,2),(45,10),(99,2),(100,98),(100,24),(100,51)

|improve this answer|||||
\$\endgroup\$
0
\$\begingroup\$

Japt, 2 bytes

vV

Returns 1 for true, 0 for false.

Try it online!

Test cases

|improve this answer|||||
\$\endgroup\$
0
\$\begingroup\$

Common Lisp, 27 Bytes

(lambda(n d)(= 0(mod n d)))

Pretty basic.

Explanation:

(lambda(n d)(            ))     | Function of two arguments
             = 0(mod n d)       | Test if n mod d == 0
|improve this answer|||||
\$\endgroup\$
0
\$\begingroup\$

W , 3 bytes

Sm!

Explanation

Sm!

With implicit input:

baSm!
baS   % Produce a,b
   m  % Produce a%b
    ! % Negate the value
|improve this answer|||||
\$\endgroup\$
-2
\$\begingroup\$

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication181
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the Maximum Range of the Array:");
            int N = Convert.ToInt32(Console.ReadLine());
            int[] div = new int[N];
            int[] num = new int[N];
            int[] quo = new int[N];
            int d = 0, n = 0, q = 0;
            Console.WriteLine("\n");
            Console.WriteLine("Enter the numbers:");
            for (n = 0; n < N; n++)
            {
                num[n] = Convert.ToInt32(Console.ReadLine());
            }
            Console.WriteLine("\n");
            Console.WriteLine("Enter the Divident values:");
            for (d = 0; d < N; d++)
            {
                div[d] = Convert.ToInt32(Console.ReadLine());
            }
            Console.WriteLine("\n");
            for (d = 0; d < N; d++)
            {
                for (n = 0; n < N; n++)
                {
                    if (d == n)
                    {
                        quo[q] = (num[n] / div[d]);
                        q++;
                    }
                }
            }
            Console.WriteLine("\n");
            Console.WriteLine("The Quotient values are:");
            for (q = 0; q < N; q++)
            {
                Console.Write("{0} ", quo[q]);
            }
            Console.WriteLine("\n");
            Console.WriteLine("d      n    output");
            for (d = 0; d < N; d++)
            {
                for (n = 0; n < N; n++)
                {
                    for (q = 0; q < N; q++)
                    {
                        if ((d == n)&&(n == q)&&(q==d))
                        {
                            if ((quo[d] * div[d]) == num[n])
                            {
                                Console.WriteLine("{0}      {1}    truthy", div[d], num[n]);
                            }
                            else
                            {
                                Console.WriteLine("{0}      {1}    False ",div[d],num[n]);
                            }
                        }
                    }
                }
            }
            Console.WriteLine("\n");
            Console.ReadLine();
        }
    }
}
|improve this answer|||||
\$\endgroup\$
  • 3
    \$\begingroup\$ This is a code golf challenge you know? Where you're trying to get the lowest amount of bytes possible? \$\endgroup\$ – Blue Oct 12 '16 at 11:41
  • 2
    \$\begingroup\$ Answers must attempt to lower their byte count to be considered a serious answer for code-golf. Essentially, make your code as small as possible, while still having it be able to run. \$\endgroup\$ – mbomb007 Oct 12 '16 at 13:31
-3
\$\begingroup\$

TCC, 1 byte (Non-competing)

v

Input is 2 numbers seperated by a space

Try it online!

|improve this answer|||||
\$\endgroup\$
  • 2
    \$\begingroup\$ This does not work with the tcc.lua file with timestamp 16-07-26 12:46 UTC, which didn't have the v command. If your answer requires a version of the language that postdates the challenge, you must label it as non-competing in the header. I'll remove my downvote when you do. \$\endgroup\$ – Dennis Jul 26 '16 at 17:07
  • \$\begingroup\$ @Dennis If you still have the downvote in, you can remove it. The post is edited. Also, you can delete the comments afterwards. \$\endgroup\$ – Erik the Outgolfer Oct 6 '16 at 15:27
1 2 3
4

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.