Count the divisors of a number

26

2

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>

jqblz

Posted 2015-11-27T06:19:14.787

Reputation: 2 062

Answers

19

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

FryAmTheEggman

Posted 2015-11-27T06:19:14.787

Reputation: 16 206

Fascinating. Nice approach – Cyoce – 2016-04-09T15:59:27.983

14

C++ C, 43 57 56 46 43 bytes

On Martin Büttner's suggestions :

i,c;f(n){for(i=c=n;i;n%i--&&--c);return c;}

Sahil Arora

Posted 2015-11-27T06:19:14.787

Reputation: 341

1Wait, 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 – 2015-11-27T14:46:37.457

@MartinBüttner Wow man wow. Seriously! /\ – Sahil Arora – 2015-11-27T14:48:53.557

1Beautiful! :~)! – sweerpotato – 2015-11-27T16:55:13.400

11

LabVIEW, 4938 Bytes

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

Eumel

Posted 2015-11-27T06:19:14.787

Reputation: 2 487

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 – 2015-11-27T09:34:09.280

i saved it and took the size of it – Eumel – 2015-11-27T09:35:06.370

And it was 4.938 bytes? Not kilobytes, for instance? – jqblz – 2015-11-27T09:37:09.063

for accuracy i took the byte count not the kb count – Eumel – 2015-11-27T09:38:23.490

4@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 – 2015-11-27T09:39:33.563

@MartinBüttner Ah, thank you. I was confused because the Snippet was parsing it as a decimal. – jqblz – 2015-11-27T09:41:48.120

By the way there was a discussion in Meta about how to score LabVIEW, http://meta.codegolf.stackexchange.com/questions/7502/programming-in-labview-how-to-measure-program-size?cb=1

– WizardOfMenlo – 2015-11-28T09:53:42.920

I am well aware, if you read the answer there you will find that it´s mine and a proposed way to count^^ – Eumel – 2015-11-28T16:57:23.817

10

Haskell, 28 bytes

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

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]

xnor

Posted 2015-11-27T06:19:14.787

Reputation: 115 687

7

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.

Adám

Posted 2015-11-27T06:19:14.787

Reputation: 37 779

6

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.

xnor

Posted 2015-11-27T06:19:14.787

Reputation: 115 687

6

Golfscript, 19 18 17 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

Sherlock9

Posted 2015-11-27T06:19:14.787

Reputation: 11 664

For the same length you could also have ~:X,{)X\%!},, – Peter Taylor – 2015-11-27T09:24:00.640

6

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.

Martin Ender

Posted 2015-11-27T06:19:14.787

Reputation: 184 808

6

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.

Dennis

Posted 2015-11-27T06:19:14.787

Reputation: 196 637

I don't think q: is allowed as it solves an essential part of the challenge. How about just [:+/0=]|~1+i. – FUZxxl – 2015-11-27T15:37:53.903

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 – 2015-11-27T16:03:57.993

Builtins that do all / almost all of the work of a challenge are usually forbidden but I can follow your reasoning for q:. – FUZxxl – 2015-11-27T16:05:13.193

1They are not. I wish they were, but they are not. – Dennis – 2015-11-27T16:08:10.690

Hrmpf hrmpf that sucks a little. – FUZxxl – 2015-11-27T16:16:49.927

4

J, 13 12 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

alephalpha

Posted 2015-11-27T06:19:14.787

Reputation: 23 988

3

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

jqblz

Posted 2015-11-27T06:19:14.787

Reputation: 2 062

3

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.

Martin Ender

Posted 2015-11-27T06:19:14.787

Reputation: 184 808

3

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

flawr

Posted 2015-11-27T06:19:14.787

Reputation: 40 560

This would have been my approach too! – Luis Mendo – 2015-11-27T12:27:23.573

Interesting that this is the same length as length(divisors(n)). – Acccumulation – 2019-04-24T20:55:57.867

@Acccumulation you'd still need to add a @(n) to make it a valid submisison – flawr – 2019-04-24T20:57:18.370

3

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.

Alex A.

Posted 2015-11-27T06:19:14.787

Reputation: 23 761

2

Jelly, 2 bytes (non-competing (again))

Æ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 :))

Erik the Outgolfer

Posted 2015-11-27T06:19:14.787

Reputation: 38 134

2

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.

Engineer Toast

Posted 2015-11-27T06:19:14.787

Reputation: 5 769

2

Japt, 3 bytes

â l

-m flag is for running all the test cases.

Try it

Embodiment of Ignorance

Posted 2015-11-27T06:19:14.787

Reputation: 7 014

2

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.

i_saw_drones

Posted 2015-11-27T06:19:14.787

Reputation: 413

2

05AB1E, 2 bytes

Ñg

Try it online or verify all test cases.

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)

Kevin Cruijssen

Posted 2015-11-27T06:19:14.787

Reputation: 67 575

2

Pyth, 8 bytes

Simple trial division.

lf!%QTSQ

Try it online here.

Maltysen

Posted 2015-11-27T06:19:14.787

Reputation: 25 023

2

PARI/GP, 6 bytes

PARI/GP have a built-in for this.

numdiv

alephalpha

Posted 2015-11-27T06:19:14.787

Reputation: 23 988

i'm not sure, but I think that according to meta, for builtins, you can't merely restate it. – Maltysen – 2015-11-27T06:35:54.733

3

@Maltysen I think it's allowed. http://meta.codegolf.stackexchange.com/a/7206/9288

– alephalpha – 2015-11-27T06:41:10.527

2

Octave, 21 20 bytes

@(n)nnz(~mod(n,1:n))

alephalpha

Posted 2015-11-27T06:19:14.787

Reputation: 23 988

I like the nnz, great usage here=) – flawr – 2015-11-27T11:05:25.743

2

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 

manatwork

Posted 2015-11-27T06:19:14.787

Reputation: 17 865

2

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.

n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳

Posted 2015-11-27T06:19:14.787

Reputation: 5 683

2

Javascript (ES6), 60 57 42 40 39 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>

Sherlock9

Posted 2015-11-27T06:19:14.787

Reputation: 11 664

2

Give up the good habits. Remove var keywords. More tips in Tips for golfing in JavaScript and Tips for Golfing in ECMAScript 6.

– manatwork – 2015-11-27T12:19:09.467

2Also 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 – 2015-11-27T12:20:38.257

2Only briefly tested: n=>{for(d=i=0;i<n;)n%++i<1&&d++;return d} – manatwork – 2015-11-27T12:21:57.123

138: n=>eval('for(d=0,i=n;i;d+=n%i--<1);d') – Mama Fun Roll – 2015-11-27T20:10:14.090

1@manatwork Why not n%++i||++d? – Neil – 2015-11-27T21:49:16.567

1Using @MartinBüttner's C suggestion saves another 2 bytes: n=>{for(d=i=n;i;n%i--&&d--);return d} – Neil – 2015-11-27T21:56:05.927

@Neil, I was distracted by other tasks when I wrote it. Realized the clumsiness just later when I saw Sahil Arora's C solution.

– manatwork – 2015-11-29T15:08:23.013

2

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.

Martin Ender

Posted 2015-11-27T06:19:14.787

Reputation: 184 808

2

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

Brad Gilbert b2gills

Posted 2015-11-27T06:19:14.787

Reputation: 12 713

2

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

TessellatingHeckler

Posted 2015-11-27T06:19:14.787

Reputation: 2 412

Very nicely hacked! – jqblz – 2015-12-16T05:45:07.727

1

MY (noncompeting), 4 bytes

Hex:

1A 3A 47 27

Explanation:

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

Zacharý

Posted 2015-11-27T06:19:14.787

Reputation: 5 710

1

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

reffu

Posted 2015-11-27T06:19:14.787

Reputation: 1 361

1

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<N<1000\$ 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<N<10^{100}\$

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.

Tau

Posted 2015-11-27T06:19:14.787

Reputation: 1 935

1

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
   +      ~    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!

Jonathan Frech

Posted 2015-11-27T06:19:14.787

Reputation: 6 681

1

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

Stephen

Posted 2015-11-27T06:19:14.787

Reputation: 12 293

1

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.

Unrelated String

Posted 2015-11-27T06:19:14.787

Reputation: 5 300

1

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.

Naruyoko

Posted 2015-11-27T06:19:14.787

Reputation: 459

1

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.

640KB

Posted 2015-11-27T06:19:14.787

Reputation: 7 149

1

Mathematica, 16 bytes

Length@*Divisors

Simple function composition of built-ins.

Martin Ender

Posted 2015-11-27T06:19:14.787

Reputation: 184 808

1

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.

El'endia Starman

Posted 2015-11-27T06:19:14.787

Reputation: 14 504

1

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π

Mego

Posted 2015-11-27T06:19:14.787

Reputation: 32 998

1

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.

undefined

Posted 2015-11-27T06:19:14.787

Reputation: 211

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

– Titus – 2016-11-28T15:07:58.173

1

O, 21 bytes

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

Sample run:

bash-4.3$ ./o o.o <<< 100
9

manatwork

Posted 2015-11-27T06:19:14.787

Reputation: 17 865

This is a placeholder until @phase posts the proper O solution. – manatwork – 2015-11-27T11:26:45.800

1

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.

lirtosiast

Posted 2015-11-27T06:19:14.787

Reputation: 20 331

I'm honestly somewhat surprised that TI-BASIC doesn't have a builtin for divisors. – jqblz – 2015-11-27T18:17:24.883

2This looks familiar... – NinjaBearMonkey – 2015-11-27T18:24:02.967

1

Jelly, non-competing

ÆDL

3 bytes; uses the builtin for divisors.

This answer is non-competing, since it uses features implemented after the challenge was posted.

lirtosiast

Posted 2015-11-27T06:19:14.787

Reputation: 20 331

1

JavaScript (ES6), 29 bytes

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

Recursive solution.

user81655

Posted 2015-11-27T06:19:14.787

Reputation: 10 181

0

C#, 53 bytes

I=>{int s=0,i=1;for(;i<=I;)if(I%i++<1)s++;return s;};

Recursive solution, 72 bytes:

I=>{return y(I,1);};y=(J,C)=>{return C==J?1:J%C<1?1+y(J,C++):y(J,C++);};

Okay, recursion was not the answer here since I needed a helper function.

Yodle

Posted 2015-11-27T06:19:14.787

Reputation: 2 378

0

Axiom 27 bytes

f(x)==(x=1=>1;#divisors(x))

results

(21) -> for i in [1,2,12,30,60,97,100] repeat output [i,f(i)]
   [1,1]
   [2,2]
   [12,6]
   [30,8]
   [60,12]
   [97,2]
   [100,9]

RosLuP

Posted 2015-11-27T06:19:14.787

Reputation: 3 036

0

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

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

Try it online!

Innat3

Posted 2015-11-27T06:19:14.787

Reputation: 791

0

Perl 5, 21 bytes

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

Try it online!

Xcali

Posted 2015-11-27T06:19:14.787

Reputation: 7 671

0

Befunge-93, 110 104 bytes

10:p010p&v>10g   >.@       |%g:0:<
`*:g:0:  <p:0+1g:0<p01+2g01<     |
0:g:*-   #v_10g1+v^        <     >

Try it online!

JPeroutek

Posted 2015-11-27T06:19:14.787

Reputation: 734

0

59 61 57 Bytes, Scala

n=>1.to(n).map(i=>println(i,1.to(n).filter(i%_==0).size))

gregam3

Posted 2015-11-27T06:19:14.787

Reputation: 1

This seems to print out the results for all the numbers from 1 to 100. Shouldn't it take input and calculate on the input? – Post Rock Garf Hunter – 2019-12-11T21:06:08.687

@WheatWizard you are correct, I was mixing it up with https://code-golf.io/divisors#python, fixed.

– gregam3 – 2019-12-12T08:37:44.640

1

It would also help to have a link to an online interpreter, like Try It Online. I'd edit one in myself, but don't know Scala, so haven't managed to actually invoke the lambda.

– Unrelated String – 2019-12-12T09:23:19.720

@UnrelatedString Thanks I'll make sure to include this in the future – gregam3 – 2019-12-12T12:23:54.877

0

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

Sherlock9

Posted 2015-11-27T06:19:14.787

Reputation: 11 664

0

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)

Jonas

Posted 2015-11-27T06:19:14.787

Reputation: 177

You can save one byte by doing: sum(mod(n,1:n)<1) – Stewie Griffin – 2015-11-27T10:45:40.550

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.) – Stewie Griffin – 2015-11-27T10:52:49.693

0

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.

J Atkin

Posted 2015-11-27T06:19:14.787

Reputation: 4 846

0

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

Dale Johnson

Posted 2015-11-27T06:19:14.787

Reputation: 509

0

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.

Paŭlo Ebermann

Posted 2015-11-27T06:19:14.787

Reputation: 1 010

0

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.

Joey

Posted 2015-11-27T06:19:14.787

Reputation: 12 260

0

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.

ConMan

Posted 2015-11-27T06:19:14.787

Reputation: 203

0

O, 20 18 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

phase

Posted 2015-11-27T06:19:14.787

Reputation: 2 540

0

Hassium, 53 Bytes

func d(i){c=0 for(n=1;n<=i;n++)i%n==0?c++:""print(c)}

See expanded and run online with test case here

Jacob Misirian

Posted 2015-11-27T06:19:14.787

Reputation: 737