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

20
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ Fascinating. Nice approach \$\endgroup\$
    – Cyoce
    Apr 9, 2016 at 15:59
14
\$\begingroup\$

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;}
\$\endgroup\$
3
  • 1
    \$\begingroup\$ 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;} \$\endgroup\$ Nov 27, 2015 at 14:46
  • \$\begingroup\$ @MartinBüttner Wow man wow. Seriously! _/\_ \$\endgroup\$ Nov 27, 2015 at 14:48
  • 1
    \$\begingroup\$ Beautiful! :~)! \$\endgroup\$ Nov 27, 2015 at 16:55
12
\$\begingroup\$

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

\$\endgroup\$
8
  • \$\begingroup\$ 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. \$\endgroup\$
    – jqkul
    Nov 27, 2015 at 9:34
  • \$\begingroup\$ i saved it and took the size of it \$\endgroup\$
    – Eumel
    Nov 27, 2015 at 9:35
  • \$\begingroup\$ And it was 4.938 bytes? Not kilobytes, for instance? \$\endgroup\$
    – jqkul
    Nov 27, 2015 at 9:37
  • \$\begingroup\$ for accuracy i took the byte count not the kb count \$\endgroup\$
    – Eumel
    Nov 27, 2015 at 9:38
  • 4
    \$\begingroup\$ @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). \$\endgroup\$ Nov 27, 2015 at 9:39
11
\$\begingroup\$

Haskell, 28 bytes

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.

\$\endgroup\$
8
\$\begingroup\$

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.

\$\endgroup\$
8
\$\begingroup\$

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.

\$\endgroup\$
6
\$\begingroup\$

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.

\$\endgroup\$
6
\$\begingroup\$

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.
\$\endgroup\$
5
  • \$\begingroup\$ I don't think q: is allowed as it solves an essential part of the challenge. How about just [:+/0=]|~1+i. \$\endgroup\$
    – FUZxxl
    Nov 27, 2015 at 15:37
  • \$\begingroup\$ 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. \$\endgroup\$
    – Dennis
    Nov 27, 2015 at 16:03
  • \$\begingroup\$ Builtins that do all / almost all of the work of a challenge are usually forbidden but I can follow your reasoning for q: . \$\endgroup\$
    – FUZxxl
    Nov 27, 2015 at 16:05
  • 1
    \$\begingroup\$ They are not. I wish they were, but they are not. \$\endgroup\$
    – Dennis
    Nov 27, 2015 at 16:08
  • \$\begingroup\$ Hrmpf hrmpf that sucks a little. \$\endgroup\$
    – FUZxxl
    Nov 27, 2015 at 16:16
6
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ For the same length you could also have ~:X,{)X\%!},, \$\endgroup\$ Nov 27, 2015 at 9:24
4
\$\begingroup\$

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.

\$\endgroup\$
4
\$\begingroup\$

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
\$\endgroup\$
0
3
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

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.
\$\endgroup\$
3
\$\begingroup\$

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))
\$\endgroup\$
3
  • \$\begingroup\$ This would have been my approach too! \$\endgroup\$
    – Luis Mendo
    Nov 27, 2015 at 12:27
  • \$\begingroup\$ Interesting that this is the same length as length(divisors(n)). \$\endgroup\$ Apr 24, 2019 at 20:55
  • \$\begingroup\$ @Acccumulation you'd still need to add a @(n) to make it a valid submisison \$\endgroup\$
    – flawr
    Apr 24, 2019 at 20:57
3
\$\begingroup\$

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.
\$\endgroup\$
3
\$\begingroup\$

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)
\$\endgroup\$
3
\$\begingroup\$

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

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

PARI/GP, 6 bytes

PARI/GP have a built-in for this.

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

Pyth, 8 bytes

Simple trial division.

lf!%QTSQ

Try it online here.

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

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 
\$\endgroup\$
2
\$\begingroup\$

Octave, 21 20 bytes

@(n)nnz(~mod(n,1:n))
\$\endgroup\$
1
  • \$\begingroup\$ I like the nnz, great usage here=) \$\endgroup\$
    – flawr
    Nov 27, 2015 at 11:05
2
\$\begingroup\$

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.

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

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.

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

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
\$\endgroup\$
2
\$\begingroup\$

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>

\$\endgroup\$
8
  • 2
    \$\begingroup\$ Give up the good habits. Remove var keywords. More tips in Tips for golfing in JavaScript and Tips for Golfing in ECMAScript 6. \$\endgroup\$
    – manatwork
    Nov 27, 2015 at 12:19
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ Nov 27, 2015 at 12:20
  • 2
    \$\begingroup\$ Only briefly tested: n=>{for(d=i=0;i<n;)n%++i<1&&d++;return d} \$\endgroup\$
    – manatwork
    Nov 27, 2015 at 12:21
  • 1
    \$\begingroup\$ 38: n=>eval('for(d=0,i=n;i;d+=n%i--<1);d') \$\endgroup\$ Nov 27, 2015 at 20:10
  • 1
    \$\begingroup\$ @manatwork Why not n%++i||++d? \$\endgroup\$
    – Neil
    Nov 27, 2015 at 21:49
2
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ Very nicely hacked! \$\endgroup\$
    – jqkul
    Dec 16, 2015 at 5:45
2
\$\begingroup\$

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.
\$\endgroup\$
2
\$\begingroup\$

Japt, 3 bytes

â l

-m flag is for running all the test cases.

Try it

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

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.

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

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