33
\$\begingroup\$

Introduction

This is a very simple challenge: simply count the divisors of a number. We've had a similar but more complicated challenge before, but I'm intending this one to be entry-level.

The Challenge

Create a program or function that, given one strictly positive integer N, outputs or returns how many divisors it has, including 1 and N.

Input: One integer > 0. You may assume that the number can be represented in your language's native numeric type.

Output: The number of positive integer divisors it has, including 1 and the number itself.

Submissions will be scored in bytes. You may find this website handy, though you may use any reasonable method for generating your byte count.

This is , so the lowest score wins!

Edit: It looks like FryAmTheEggman's 5-byte Pyth answer is the winner! Feel free to submit new answers, though; if you can get something shorter, I'll change the accepted answer.

Test Cases

ndiv(1) -> 1
ndiv(2) -> 2
ndiv(12) -> 6
ndiv(30) -> 8
ndiv(60) -> 12
ndiv(97) -> 2
ndiv(100) -> 9

Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

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 you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

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

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

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

var QUESTION_ID=64944,OVERRIDE_USER=45162;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?([\d.]+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <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><div id="language-list"> <h2>Winners 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><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>

\$\endgroup\$

68 Answers 68

2
\$\begingroup\$

Brachylog, 2 bytes

fl

Try it online!

Takes input through its input variable and outputs through its output variable.

f     The list of factors of
      the input variable
 l    has length equal to
      the output variable.

This exact same predicate, taking input through its output variable and outputting through its input variable, solves this challenge instead.

\$\endgroup\$
2
\$\begingroup\$

krrp, 22 bytes

^n:,^k:&k+=%[email protected].

Try it online!


Explanation

^n:       ~ an anonymous function of arity one
 ,^k:     ~  apply the following function (*) of arity one
  &k      ~   if `k` is zero, return zero; else
   +      ~    add
    =%nk0 ~     boolean (if `k` is a divisor of `n`)
    @-k1. ~     to the current function (*) itself applied to `k-1`
 n.       ~  to `n`

Try it online!

\$\endgroup\$
2
\$\begingroup\$

JavaScript, 3230 bytes

n=(x,y=x)=>y?n(x,y-1)+!(x%y):1

Ungolf:

n=(x,y=x)=>                     //function declaration with y=x preset
           y?                   //check if y=0
             n(x,y+1)           //next divisor(current-1)
                     +!(x%y)    //1 if y is a divisor of x, 0 if not. Or, if x mod y=0.
                            :0  //if y=1, then 0(base case)

32B->30B, -2B for reversing the loop, reducing the condition x-y to y.

\$\endgroup\$
2
\$\begingroup\$

x86-16 machine code, 15 bytes

 8B C8          MOV  CX, AX                 ; store input as counter
            DEC_LOOP: 
 50             PUSH AX                     ; save input number
 88 0E 0108     MOV  BYTE PTR[AAM1+1], CL   ; modify AAM code operand's second byte
            AAM1: 
 D4 0A          AAM                         ; ZF = ( AL % CL == 0 )
 75 01          JNZ  END_LOOP               ; if remainder not 0, continue loop
 43             INC  BX                     ; otherwise increment BX
            END_LOOP: 
 58             POP  AX                     ; restore input number
 E2 F3          LOOP DEC_LOOP

Input is AX, output is BX.

This uses (abuses) the arbitrary base ability of the AAM instruction to check if each factor is divisible. It self-modifies the second byte of the opcode of the AAM with the divisor on each iteration of the loop.

\$\endgroup\$
2
\$\begingroup\$

Desmos, 30 bytes

\sum_{n=1}^m(1-sign(mod(m,n)))

Alternatively:

m-sign(mod(m,[1,...,m])).total

View them online

\$\endgroup\$
1
  • \$\begingroup\$ You can save a few bytes in your first answer by replacing 1-sign(...) with 0^{...}: \sum_{n=1}^m0^{mod(m,n)} \$\endgroup\$
    – Aiden Chow
    Commented May 22, 2022 at 21:53
2
\$\begingroup\$

Stax, 3 bytes

:d%

Run and debug it

It's the same size when packed.

\$\endgroup\$
2
\$\begingroup\$

Burlesque, 6 bytes

rifcL[

Try it online!

Explanation:

ri     # Read integer from input string
  fc   # Get list of factors
    L[ # Get length and implicitly output
\$\endgroup\$
2
\$\begingroup\$

Neim, 1 byte

𝐜   # Count Divisors

Try it online!

I posted this on a duplicate which got closed, so I figured I'd post it here.

\$\endgroup\$
2
\$\begingroup\$

Rockstar, 90 bytes

listen to N
X's0
D's0
while N-X
let X be+1
let M be N/X
turn up M
let D be+M is N/X

say D

Try it here (Code will need to be pasted in)

\$\endgroup\$
2
\$\begingroup\$

Jelly, 3 bytes

ÆDL

Uses the builtin for divisors.

\$\endgroup\$
2
\$\begingroup\$

Add++, 32 29 bytes

+?
Fx,`r,x%i,=0,Ir,,`y,,+1
Oy

Try it online!

Explained (old)

x:?             # Set x to the input
Fx,             # For i in range(x):
    `r,         #       Set the active variable r AND
    x%i,        #       Assign to it the result of x%i
    r=0,        #       And then the result of r==0
    Ir,,        #       If r == 1:
        `y,,    #           Set the active variable to y AND
        y+1     #           Assign to it y + 1
Oy              # Output variable y
\$\endgroup\$
1
  • 1
    \$\begingroup\$ 29 bytes. Taking advantage of the fact you can omit variables when they’re active, and +? works for taking integer input rather than x:? \$\endgroup\$ Commented Sep 23, 2020 at 1:56
1
\$\begingroup\$

Mathematica, 16 bytes

Length@*Divisors

Simple function composition of built-ins.

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

Minkolang 0.13, 16 bytes

ndd[0ci1+%,-]-N.

Check all cases here.

Explanation

ndd           Takes number from input and duplicates it twice (n)
[             Opens for loop that runs n times
 0c           Copies bottom of stack to top (n)
   i1+        Loop counter + 1 (d)
      %       Modulo - pops d,n, then pushes n%d
       ,      Not - 1 if equal to 0, 0 otherwise
        -     Subtract
         ]    Close for loop
-             Subtract (n - 1 for each non-divisor)
N.            Output as number and stop.
\$\endgroup\$
1
\$\begingroup\$

O, 21 bytes

0[Q{Qn)%}d]{n{}{)}?}d

Sample run:

bash-4.3$ ./o o.o <<< 100
9
\$\endgroup\$
1
  • \$\begingroup\$ This is a placeholder until @phase posts the proper O solution. \$\endgroup\$
    – manatwork
    Commented Nov 27, 2015 at 11:26
1
\$\begingroup\$

PHP, 61 bytes

<?$x=$_GET['x'];for($i=1;$i<=$x;$i++)$c+=$x%$i==0?1:0;echo$c;

I don't know if there's a shorter way to get input in PHP, so I use $_GET.

\$\endgroup\$
1
  • \$\begingroup\$ There´s no shorter input, only $argv[1] which has the same length; but here are some tips to golf this down to 42 bytes \$\endgroup\$
    – Titus
    Commented Nov 28, 2016 at 15:07
1
\$\begingroup\$

TI-BASIC, 10 bytes

sum(not(fPart(Ans/randIntNoRep(1,Ans

This won't work for numbers >999, since that's the maximum size of a list.

\$\endgroup\$
2
  • \$\begingroup\$ I'm honestly somewhat surprised that TI-BASIC doesn't have a builtin for divisors. \$\endgroup\$
    – jqkul
    Commented Nov 27, 2015 at 18:17
  • 2
    \$\begingroup\$ This looks familiar... \$\endgroup\$ Commented Nov 27, 2015 at 18:24
1
\$\begingroup\$

Seriously, 17 bytes

,;n;;╟@RZ`i@%Y`MΣ

Try it online with explanation

If my prime factorization function had been working before this challenge, I could get 9 bytes:

,w`iXu`Mπ
\$\endgroup\$
0
1
\$\begingroup\$

JavaScript (ES6), 29 bytes

f=(n,i=n)=>i&&f(n,i-1)+!(n%i)

Recursive solution.

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

MY (noncompeting), 4 bytes

Hex:

1A 3A 47 27

Explanation:

1A - Input from STDIN
3A - List of factors
47 - Length
27 - Output (with newline)
\$\endgroup\$
1
\$\begingroup\$

Forth (gforth), 41 bytes

: f 0 over 1+ 1 do over i mod 0= - loop ;

Try it online!

Code Explanation

: f            \ start a new word definition
  0 over 1+ 1  \ set up loop parameters and a value to store the count in
  do           \ loop from 1 to n
    over       \ get n and put it on top of the stack
    i mod 0=   \ check if the current loop index is a divisor of n
    -          \ if so, subtract it from the counter (-1 = true in forth)
  loop         \ end the loop
;              \ end the word definition
\$\endgroup\$
1
\$\begingroup\$

C# (Visual C# Interactive Compiler), 42 bytes

n=>Enumerable.Range(1,n).Count(x=>n%x==0);

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Suggest n%x<1 instead of n%x==0 \$\endgroup\$
    – ceilingcat
    Commented Oct 29, 2020 at 5:40
1
\$\begingroup\$

Perl 5, 21 bytes

$_-=grep"@F"%$_,1..$_

Try it online!

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

Knight, 31 bytes

O;=x+=z=y 0P;W>x y=z+z!%x=y+yTz

Try it online!

; go brrrrr

This is a good example of how ordering and chaining can save bytes in Knight (in a manner similar to recursion).

; evaluates two statements and returns the second result which is useful when you have case conflicts.

OUTPUT
   # Chain all but the last z
   # x = prompt(), z = y = 0
   ; (=x + (=z=y 0) PROMPT)
   # Loop for each y up to x
   ; WHILE > x y
       # If x % ++y == 0, increment z
       = z + z (! % x (= y + y 1))
   # The actual statement outputted at the end
   : z
\$\endgroup\$
1
\$\begingroup\$

Vyxal, 2 bytes

KL

Try it Online!

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

MATLAB, 19 21 bytes

Assume, n is defined as the number

sum(mod(n,1:n)==0)

If the function style is required

function t(n)
sum(mod(n,1:n)==0)

Edit: As explained in the comments fixed as an anonymous function and further golfed:

@(n)sum(mod(n,1:n)<1)
\$\endgroup\$
2
  • \$\begingroup\$ You can save one byte by doing: sum(mod(n,1:n)<1) \$\endgroup\$ Commented Nov 27, 2015 at 10:45
  • \$\begingroup\$ Jonas, you can make it an anonymous function by simply adding an @(n) in front of it. You can then call the function: ans(12). (i.e. you don't need function.) \$\endgroup\$ Commented Nov 27, 2015 at 10:52
0
\$\begingroup\$

Groovy, 34 bytes

f={n->(1..n).findAll{n%it<1}.size}

Provides function f that finds all divisors of n and returns the size.

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

Candy, 11 bytes

With the value to test already pushed onto the stack:

~xR(XW%nh)Z

This translates into long form:

peekA   # copy argument from stack into register A
XGetsA  # X := A
range1  # pop argument from stack, push arg, arg - 1, arg - 2, ... 1
while   # while stack not empty
  pushX
  swap    # swap two top stack entries
  mod     # iterated value mod X
  not     # modulo == 0 ?
  popAddZ # Z := Z + popped
endwhile
pushZ     # push Z onto stack, on termination a single value popped and printed
\$\endgroup\$
0
\$\begingroup\$

Pyth, 15 bytes

Number of divisors, using the prime factorization built-in P, and to avoid an error with 0 < input < 2, where P1 == [] and would break the lambda, it returns 1, since there's only one divisor in that case. Special thanks to @orlp

Try it online here.

JrPQ8?J*FmhhdJ1
\$\endgroup\$
0
\$\begingroup\$

Ceylon, 54 47

Integer d(Integer n)=>(1..n).count((i)=>n%i<1);

This defines a function d which is almost straightforward: Take the list of integers from 1 to n (both inclusive), and apply to each the anonymous function (i) => n%i < 1 (which is a shorter way of writing (i) => i.divides(n)), and count how often it returns true.

Formatted it could look like this:

Integer d(Integer n) =>
        (1..n).count((i) => n%i < 1);

Here we have two versions of 54 bytes each:

Integer d(Integer c)=>{for(i in 1..n)if(n%i<1)i}.size;

Integer d(Integer c)=>sum{1,for(i in 2..n)if(n%i<1)1};

Both use an Iterable comprehension composed of a for and an if clause, with one using .size and the other one using sum, but with an additional literal first entry to convince the compiler it is not empty.

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

PowerShell, 40 bytes

filter d($n){(1..$n|?{!($n%$_)}).Count}

or

filter d($n){1..$n|%{$s+=+!($n%$_)};$s}

Both versions have the same length. Can't seem to get it shorter.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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