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

Pyth, 5

l{yPQ

Uses the subsets operation on the prime factors of the input, then keeps only the unique lists of factors and returns this count.

Test Suite

Explanation

Using 25 as an example, so that the subset list isn't very long

l{yPQ     ## implicit:  Q = eval(input()) so Q == 25
PQ     ## Prime factors of Q, giving [5, 5]
y       ## All subsets, giving [[], [5], [5], [5, 5]]
{        ## Unique-fiy, giving [[], [5], [5, 5]]
l         ## Length, print implicity
• Fascinating. Nice approach – Cyoce Apr 9 '16 at 15:59

C++ C, 43575646 43 bytes

On Martin Büttner's suggestions :

i,c;f(n){for(i=c=n;i;n%i--&&--c);return c;}
• Wait, let's count both of them down instead, for 43: i,c;f(n){for(i=c=n;i;n%i--&&--c);return c;} – Martin Ender Nov 27 '15 at 14:46
• @MartinBüttner Wow man wow. Seriously! _/\_ – Sahil Arora Nov 27 '15 at 14:48
• Beautiful! :~)! – sweerpotato Nov 27 '15 at 16:55

LabVIEW, 4938 Bytes

Well its obviously not suited for code golf but whatever, so for my first post and the lolz here goes.

• Welcome to Programming Puzzles and Code Golf! How did you score this, if you don't mind me asking? I couldn't find any precedent on Meta. – jqblz Nov 27 '15 at 9:34
• i saved it and took the size of it – Eumel Nov 27 '15 at 9:35
• And it was 4.938 bytes? Not kilobytes, for instance? – jqblz Nov 27 '15 at 9:37
• for accuracy i took the byte count not the kb count – Eumel Nov 27 '15 at 9:38
• @bkul I think the confusion is due to the ., which I'm pretty sure is meant as a thousand separator, not a decimal point (as is common in some languages). – Martin Ender Nov 27 '15 at 9:39

f n=sum[0^mod n i|i<-[1..n]]

Try it online!

The trick here is to test whether a remainder is 0 using the indicator function 0^.

0^0 = 1
0^_ = 0

This works because any positive power of 0 is 0, whereas 0^0 is combinatorially the empty product of 1.

Compare this to filtering

f n=sum[1|i<-[1..n],mod n i<1]

28 bytes

f n=sum[1|0<-mod n<$>[1..n]] Try it online! An alternative method using matching on a constant. The <$> infix map might postdate this challenge.

Python 2, 37 bytes

f=lambda n,i=1:i/n or(n%i<1)+f(n,i+1)

A recursive function. The optional input i in the divisor being tested. The expression (n%i<1) tests divisibility, with True (which equals 1) for divisors. The result is added to the recusive expression for i+1. When i==n is reached, the integer floor-division i/n evaluates to 1, and that value is returned as the base case, accounting for n itself being a divisor of n.

38:

lambda n:sum(n%-~i<1for i in range(n))

An anonymous function. Tests all possible divisors 1 through n. This is shifted up from 0 through n-1 in range(n) using -~, which adds 1. Summing the bools uses the fact that Python treats True/False as 1/0.

Dyalog APL, 7 6 bytes

≢∘∪⊢∨⍳

It is an unnamed function that can be named and then reused for each (¨) test case as follows:

f ← ≢∘∪⊢∨⍳
f¨ 1 2 12 30 60 97 100
1 2 6 8 12 2 9

Explanation:

┌─┴──┐
∪  ┌─┼─┐
∘  │ ∨ │
̸≡  ⊢   ⍳

Count the unique of the GCD of itself and each of the integers-until .

Thanks to ngn for saving a byte.

Old version: +/0=⍳|⊢

This is how it works:

┌─┴─┐
/ ┌─┼───┐
┌─┘ 0 = ┌─┼─┐
+       ⍳ | ⊢

⍳|⊢ 1-through-argument division-remainder argument
0= Boolean if 0 is equal to the division rest
+/ Sum of the boolean, i.e. count of ones.

Retina, 17 bytes

(?<=(.+))(?=\1*$) Input in unary, output in decimal. Try it online. When invoked with a single regex, Retina simply counts the matches. The regex itself matches a position, where the unary number to the left of it is a divisor of the entire input. I'm also making use of the fact that lookarounds are atomic, so that I don't need to use a ^ anchor. The first lookbehinds simply captures the entire prefix in group 1. This can never fail, so after the lookbehind we know that's what's in group 1 and it won't change any more. The lookahead then checks if we can reach the end of the string by repeating the captured string (our potential divisor) 0 or more times. J, 10 bytes [:*/1+_&q: This is an unnamed, monadic verb. It calculates σ0(∏pkαk) as ∏(αk + 1). Try it online with J.js. How it works [:*/1+_&q: Right argument: y _&q: Compute all exponents of the prime factorization of y. 1+ Add 1 to each exponent. [:*/ Reduce by mutiplication. • I don't think q: is allowed as it solves an essential part of the challenge. How about just [:+/0=]|~1+i. – FUZxxl Nov 27 '15 at 15:37 • That would be a duplicate of this answer. Also, built-ins are not forbidden by default, and the challenge doesn't seem to mention them. – Dennis Nov 27 '15 at 16:03 • Builtins that do all / almost all of the work of a challenge are usually forbidden but I can follow your reasoning for q: . – FUZxxl Nov 27 '15 at 16:05 • They are not. I wish they were, but they are not. – Dennis Nov 27 '15 at 16:08 • Hrmpf hrmpf that sucks a little. – FUZxxl Nov 27 '15 at 16:16 Golfscript, 191817 13 bytes With thanks to Martin Büttner. ~.,\{\)%!}+,, How it works ~ Evaluate the input, n ., Duplicate the input, create array [0..n-1] \ Swap array and n { }+ Add n to block == {n block} \ Swap n with i in array ) Increment i % n mod i ! Logical not so that 1 if divisible by n else 0 , Filter array using block for all i divisible by n , Get length of the filtered array, the answer Also From @Peter Taylor, also in 13 bytes. ~:X,{)X\%!},, How it works ~ Evaluate the input :X Store input in variable X , Create array [0..X-1] { }, Filter array using the following block ) Increment i in array X\ Add X to stack, swap with i % X mod i, ! Logical not so that 1 if divisible by n else 0 , Get length of the filtered array, the answer • For the same length you could also have ~:X,{)X\%!},, – Peter Taylor Nov 27 '15 at 9:24 J, 1312 11 bytes My first golf in J. I'm still learning it. Saved a byte thanks to Dennis. Saved one more byte thanks to randomra. 1+/@,0=i.|] Explanation: 1+/@,0=i.|] i. the array 0 .. n-1 |] mod n 0= replace 0 by 1, and nonzero entries by 0 1 , prepend 1 to the array +/@ take the sum Arcyóu, 12 bytes Let's get the party started! (F(x)(_(d/ x This uses the built-in function d/. Here's a version without the built-in (27 bytes): (F(x)(](+(f i(_ 1 x)(‰ x i Explanation: (F(x) ; Anonymous function with one parameter x (] ; Increment (+ ; Sum (f i(_ 1 x) ; For i in range from 1 to x-1 inclusive: (‰ x i ; x divisible by i CJam, 11 bytes ri_,:)f%0e= Test it here. Explanation CJam doesn't have a built-in for this, so we're doing trial division. ri e# Read input and convert to integer N. _, e# Duplicate and turn into range [0 1 ... N-1] :) e# Increment each element in the range to get [1 2 ... N] f% e# Take N modulo each of the list elements. 0e= e# Count the zeroes. Bonus Here is an interesting solution at 12 bytes (which I suspect might be shortest in a language like J): ri_)2m*::*e= The result is equal to the number of times n appears in an n x n multiplication table: ri e# Read input and convert to integer N. _) e# Duplicate and increment. 2m* e# Take Cartesian product of [0 1 ... N] with itself. ::* e# Compute the product of each pair. e= e# Count the occurrences of N. Matlab, 20 bytes Perform k mod n for every k = 1,...,n, then perform not (which turns every nonzer to zero and every zero to 1) and sum up all those values. @(n)sum(~mod(n,1:n)) • This would have been my approach too! – Luis Mendo Nov 27 '15 at 12:27 • Interesting that this is the same length as length(divisors(n)). – Acccumulation Apr 24 '19 at 20:55 • @Acccumulation you'd still need to add a @(n) to make it a valid submisison – flawr Apr 24 '19 at 20:57 Julia, 20 bytes n->sum(i->n%i<1,1:n) This is an anonymous function that works as follows: For each integer from 1 to the input, test whether the input modulo the integer is zero. If so, the value will be true, otherwise false. We sum over the booleans which are implicitly cast to integers, yielding the number of divisors. A much cooler (though also much longer) solution, included for the sake of completeness, is n->prod(collect(values(factor(n))).+1) This gets the canonical factorization of n, i.e. \prod_{i=1}^k p_i^e_i, and computes the divisor function as τ(n) = \prod_{i=1}^k e_i + 1. Excel Formula, 42 28 bytes Edit: I just realised I do not need to use INDIRECT, saving 14 bytes! The following should be entered as an array formula (Ctrl+Shift+Enter): =SUM(--NOT(MOD(N,ROW(1:N)))) Where N is the number to test. Examples: {SUM(--NOT(MOD(32,ROW(1:32))))} Result: 6 {SUM(--NOT(MOD(144,ROW(1:144))))} Result: 15 Explanation: SUM(--NOT(MOD(N,ROW(1:N)))) Full formula ROW(1:N) Generates an array of row numbers e.g {1;2;3;4;...N} MOD(N,ROW(1:N)) Does N MOD {1;2;3;4;,...N} NOT(MOD(N,ROW(1:N))) Coerces zeros to ones, so that they may be counted, but actually returns an array of TRUE;FALSE;FALSE;... --NOT(MOD(N,ROW(1:N))) Coerces the TRUEs to 1s and FALSEs to 0s. SUM(--NOT(MOD(N,ROW(1:N)))) Sum the ones for the result. 05AB1E, 2 bytes Ñg Explanation: Pretty straight-forward, but here it is anyway: Ñ # Push a list of divisors of the (implicit) input-integer # i.e. 100 → [1,2,4,5,10,20,25,50,100] g # Pop and push the length of this list # i.e. [1,2,4,5,10,20,25,50,100] → 9 # (which is output implicitly as result) Jelly, 2 bytes Æd Try it online! I think this uses features implemented after the other Jelly answer. Comment if I'm wrong though (I can't look each commit in the row, you know :)) PARI/GP, 6 bytes PARI/GP have a built-in for this. numdiv Pyth, 8 bytes Simple trial division. lf!%QTSQ Ruby, 27 bytes ->n{(1..n).count{|i|n%i<1}} Sample run: 2.1.5 :001 > ->n{(1..n).count{|i|n%i<1}}[100] => 9 Octave, 21 20 bytes @(n)nnz(~mod(n,1:n)) • I like the nnz, great usage here=) – flawr Nov 27 '15 at 11:05 Regex (.NET), 33 bytes ^((?=.*$(?<=^\2*(.+?(?>\2?)))).)+

Assuming input and output are in unary, and the output is taken from the main match of the regex.

Break down of the regex:

• .*$ets the pointer to the end of the string so that we have the whole input x in one direction. • (?<=^\2*(.+?(?>\2?))) matches from right to left and checks for divisor by looping from x to 0. • (.+?(?>\2?)) is a "variable" which starts from 1 in the first iteration and continues from the number in previous iteration and loops up to x. • ^\2* checks whether x is a multiple of "variable". It basically has the same idea as my answer to Calculate Phi (not Pi). Only the check is different. Test the regex at RegexStorm. Labyrinth, 33 bytes ?:} :{:}%{{ @ } " ) !{("{;"}} Try it online. This implements trial division. I'll add a full explanation later. It's probably not optimal, but I'm having a hard time coming up with something shorter. Perl 6, 17 bytes {[+]$_ X%%1..$_} # 17 usage: say {[+]$_ X%%1..$_}(60); # 12␤ my$code = {[+] $_ X%%1..$_};

say $code(97); # 2␤ my &code =$code;
say code 92; # 6

Javascript (ES6), 6057424039 37 bytes

This can probably be golfed better.

n=>{for(d=i=n;i;n%i--&&d--);return d}

Edit 1: I was right. Removed the braces after the for loop.

Edit 2: Golfed to 40 bytes with thanks to manatwork and Martin Büttner.

Edit 3: Saving a byte by basing the function on the C answer above.

Edit 4: Thanks to ןnɟuɐɯɹɐןoɯ and Neil, but I can't get the eval to work.

Edit 5: Forgot to remove the eval.

Test

n = <input type="number" oninput='result.innerHTML=(

n=>{for(d=i=n;i;n%i--&&d--);return d}

)(+this.value)' /><pre id="result"></pre>

• Give up the good habits. Remove var keywords. More tips in Tips for golfing in JavaScript and Tips for Golfing in ECMAScript 6. – manatwork Nov 27 '15 at 12:19
• Also give up the bad habits: when you've got a choice between ++i and i++, choose the former (this has nothing to do with golfing). Also n%i<1 should save a byte. – Martin Ender Nov 27 '15 at 12:20
• Only briefly tested: n=>{for(d=i=0;i<n;)n%++i<1&&d++;return d} – manatwork Nov 27 '15 at 12:21
• 38: n=>eval('for(d=0,i=n;i;d+=n%i--<1);d') – Mama Fun Roll Nov 27 '15 at 20:10
• @manatwork Why not n%++i||++d? – Neil Nov 27 '15 at 21:49

PowerShell, 34 bytes

param($x)(1..$x|?{!($x%$_)}).Count

e.g.

PS C:\temp> .\divisors-of-x.ps1 97
2
• create a list of numbers from 1 to x, feed them into the pipeline |
• filter the pipeline on (x % item == 0), by implicitly casting the modulo result as a boolean and then inverting it using ! so divisors become $true and are allowed through; using the builtin alias ? for Where-Object • gather up () and .Count how many items got through the filter • Very nicely hacked! – jqblz Dec 16 '15 at 5:45 Taxi, 2143 bytes Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 1 l 2 r.Pickup a passenger going to Cyclone.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:n 1 r.Go to Cyclone:n 1 l.Pickup a passenger going to Firemouth Grill.Pickup a passenger going to Joyless Park.Go to Firemouth Grill:s 1 l 2 l 1 r.Go to Joyless Park:e 1 l 3 r.[i][Check next value n-i]Go to Zoom Zoom:w 1 r 2 l 2 r.Go to Sunny Skies Park:w 2 l.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l.Pickup a passenger going to Divide and Conquer.Pickup a passenger going to Sunny Skies Park.Go to Joyless Park:n 2 r 2 r 2 l.Pickup a passenger going to Cyclone.Go to Sunny Skies Park:w 1 r 2 l 2 l 1 l.Go to Cyclone:n 1 l.Pickup a passenger going to Joyless Park.Pickup a passenger going to Divide and Conquer.Go to Divide and Conquer:n 2 r 2 r 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:e 1 l 1 l 2 l.Pickup a passenger going to Trunkers.Pickup a passenger going to Equal's Corner.Go to Trunkers:s 1 l.Pickup a passenger going to Equal's Corner.Go to Equal's Corner:w 1 l.Switch to plan "F" if no one is waiting.Pickup a passenger going to Knots Landing.Go to Firemouth Grill:n 3 r 1 l 1 r.Pickup a passenger going to The Underground.Go to The Underground:e 1 l.Pickup a passenger going to Firemouth Grill.Go to Knots Landing:n 2 r.Go to Firemouth Grill:w 1 l 2 r.Go to Joyless Park:e 1 l 3 r.Switch to plan "N".[F][Value not a divisor]Go to Joyless Park:n 3 r 1 r 2 l 4 r.[N]Pickup a passenger going to The Underground.Go to The Underground:w 1 l.Switch to plan "E" if no one is waiting.Pickup a passenger going to Joyless Park.Go to Joyless Park:n 1 r.Switch to plan "i".[E]Go to Sunny Skies Park:n 3 l 2 l 1 l.Pickup a passenger going to What's The Difference.Go to Firemouth Grill:s 1 l 1 l 1 r.Pickup a passenger going to What's The Difference.Go to What's The Difference:w 1 l 1 r 2 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:e 3 r.Pickup a passenger going to Post Office.Go to Post Office:n 1 l 1 r. Try it online! Ungolfed: Go to Post Office: west 1st left 1st right 1st left. Pickup a passenger going to The Babelfishery. Go to The Babelfishery: south 1st left 1st right. Pickup a passenger going to Cyclone. Go to Cyclone: north 1st left 1st left 2nd right. Pickup a passenger going to Cyclone. Pickup a passenger going to Sunny Skies Park. Go to Sunny Skies Park: north 1st right. Go to Cyclone: north 1st left. Pickup a passenger going to Firemouth Grill. Pickup a passenger going to Joyless Park. Go to Firemouth Grill: south 1st left 2nd left 1st right. Go to Joyless Park: east 1st left 3rd right. [i] [Check next value n-i] Go to Zoom Zoom: west 1st right 2nd left 2nd right. Go to Sunny Skies Park: west 2nd left. Pickup a passenger going to Cyclone. Go to Cyclone: north 1st left. Pickup a passenger going to Divide and Conquer. Pickup a passenger going to Sunny Skies Park. Go to Joyless Park: north 2nd right 2nd right 2nd left. Pickup a passenger going to Cyclone. Go to Sunny Skies Park: west 1st right 2nd left 2nd left 1st left. Go to Cyclone: north 1st left. Pickup a passenger going to Joyless Park. Pickup a passenger going to Divide and Conquer. Go to Divide and Conquer: north 2nd right 2nd right 1st right. Pickup a passenger going to Cyclone. Go to Cyclone: east 1st left 1st left 2nd left. Pickup a passenger going to Trunkers. Pickup a passenger going to Equal's Corner. Go to Trunkers: south 1st left. Pickup a passenger going to Equal's Corner. Go to Equal's Corner: west 1st left. Switch to plan "F" if no one is waiting. Pickup a passenger going to Knots Landing. Go to Firemouth Grill: north 3rd right 1st left 1st right. Pickup a passenger going to The Underground. Go to The Underground: east 1st left. Pickup a passenger going to Firemouth Grill. Go to Knots Landing: north 2nd right. Go to Firemouth Grill: west 1st left 2nd right. Go to Joyless Park: east 1st left 3rd right. Switch to plan "N". [F] [Value not a divisor] Go to Joyless Park: north 3rd right 1st right 2nd left 4th right. [N] Pickup a passenger going to The Underground. Go to The Underground: west 1st left. Switch to plan "E" if no one is waiting. Pickup a passenger going to Joyless Park. Go to Joyless Park: north 1st right. Switch to plan "i". [E] Go to Sunny Skies Park: north 3rd left 2nd left 1st left. Pickup a passenger going to What's The Difference. Go to Firemouth Grill: south 1st left 1st left 1st right. Pickup a passenger going to What's The Difference. Go to What's The Difference: west 1st left 1st right 2nd right 1st left. Pickup a passenger going to The Babelfishery. Go to The Babelfishery: east 3rd right. Pickup a passenger going to Post Office. Go to Post Office: north 1st left 1st right. Explanation: Convert stdin to a number and store it in three locations for three purposes: Original (Sunny Skies Park) Counter for tested values (Joyless Park) Counter for divisors found (Firemouth Grill) Divide the original by each Joyless Park value in turn. If the division result equals the truncated division result, then it's a divisor. When a divisor is found, subtract one from Firemouth Grill. Repeat until Joyless Park hits zero. Pickup the original from Sunny Skies Park and subtract the value from Firemouth Grill. Convert the result to a string and print to stdout. Japt, 3 bytes â l -m flag is for running all the test cases. Try it TI-BASIC, 14 bytes sum(not(fPart(Ans/cumSum(binomcdf(Ans-1,0 Input is in Ans. Output is in Ans and is implicitly printed. This submission will only work for $$\1 due to limitations in the TI calculators. Examples: 25 25 prgmCDGF14 3 100 100 prgmCDGF14 9 Explanation: sum(not(fPart(Ans/cumSum(binomcdf(Ans-1,0 ;full program binomcdf(Ans-1,0 ;generate a list of 1s whose length is the input cumSum( ;calculate the cumulative sum Ans/ ;divide the input by each term fPart( ;get the fractional part of each element not( ;logically negate each term ; 0 becomes 1 ; everything else becomes 0 sum( ;sum the list ;implicit print of "Ans" If the above submission does not suffice, then the following 24 byte submission also works for $$\0 Ans→N:0:For(I,1,N:Ans+not(fPart(N/I:End:Ans Examples: 25 25 prgmCDGF14 3 100 100 prgmCDGF14 9 Explanation: Ans→N:0:For(I,1,N:Ans+not(fPart(N/I:End:Ans ;full program Ans→N ;store the input in "N" 0 ;leave 0 in "Ans" For(I,1,N End ;loop over all integers in [1,N] Ans+not(fPart(N/I ;increment "Ans" if the current "I" ; is a factor of "N" Ans ;leave "Ans" as the last expression ;implicit print of "Ans" Note: TI-BASIC is a tokenized language. Character count does not equal byte count. cQuents, 3 bytes Lz$

Try it online!

Explanation

:Lz$: (implicit) given input n, output nth term in sequence each term in sequence equals: L length ( ) z divisors ( )$                                                        index