# 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


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

# 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>

# 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.

# krrp, 22 bytes

^n:,^k:&k+=%nk0@-k1.n.


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
=%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!

# 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.

# 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.

# Desmos, 30 bytes

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


Alternatively:

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


View them online

# Stax, 3 bytes

:d%


Run and debug it

It's the same size when packed.

# 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


# 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.

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

## Jelly, 3 bytes

ÆDL


Uses the builtin for divisors.

+?
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

• 29 bytes. Taking advantage of the fact you can omit variables when they’re active, and +? works for taking integer input rather than x:? Sep 23 '20 at 1:56

## Mathematica, 16 bytes

Length@*Divisors


Simple function composition of built-ins.

## 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.


# O, 21 bytes

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


Sample run:

bash-4.3$./o o.o <<< 100 9  • This is a placeholder until @phase posts the proper O solution. Nov 27 '15 at 11:26 # 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.

• 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 Nov 28 '16 at 15:07 ## 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. • I'm honestly somewhat surprised that TI-BASIC doesn't have a builtin for divisors. Nov 27 '15 at 18:17 • This looks familiar... Nov 27 '15 at 18:24 ## Seriously, 17 bytes ,;n;;╟@RZi@%YMΣ  Try it online with explanation If my prime factorization function had been working before this challenge, I could get 9 bytes: ,wiXuMπ  # JavaScript (ES6), 29 bytes f=(n,i=n)=>i&&f(n,i-1)+!(n%i)  Recursive solution. # MY (noncompeting), 4 bytes Hex: 1A 3A 47 27  Explanation: 1A - Input from STDIN 3A - List of factors 47 - Length 27 - Output (with newline)  # 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  ## C# (Visual C# Interactive Compiler), 42 bytes n=>Enumerable.Range(1,n).Count(x=>n%x==0);  Try it online! • Suggest n%x<1 instead of n%x==0 Oct 29 '20 at 5:40 # Perl 5, 21 bytes $_-=grep"@F"%$_,1..$_


Try it online!

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

• You can save one byte by doing: sum(mod(n,1:n)<1) Nov 27 '15 at 10:45
• 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.) Nov 27 '15 at 10:52

# 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.

# 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


# 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


## 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.

# 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.

# R, 13 bytes

Assuming that the input is stored in the variable named N.

sum(N%%1:N==0)


Generates a vector of integers from 1 to N, takes N mod each of them, and counts how many of them are 0.

# O, 2018 15 bytes

[H,;]{Qn%0=}d]+

[            ]+ Find the sum of
H,;]            a list of numbers from the input to 1
{Qn%0=}d    where we find the mod of the input and each number in the list