title: Count the divisors of a number

text:
# Question
Title: Count the divisors of a number
# 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>
```

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

```
> 20 votes

# Answer
# ~~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;}

```
> 14 votes

# Answer
## LabVIEW, 4938 Bytes

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

# Answer
# 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.
> 11 votes

# Answer
## 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`.
> 8 votes

# Answer
# 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.
> 8 votes

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

```
> 6 votes

# Answer
## 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.
> 6 votes

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

```
> 6 votes

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

```
> 4 votes

# Answer
# 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`.
> 4 votes

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

```
> 3 votes

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

```
> 3 votes

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

```
> 3 votes

# Answer
# 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 :))
> 3 votes

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

```
> 3 votes

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

```
> 3 votes

# Answer
# Pyth, 8 bytes

Simple trial division.

```
lf!%QTSQ

```

Try it online here.
> 2 votes

# Answer
# PARI/GP, 6 bytes

PARI/GP have a built-in for this.

```
numdiv

```
> 2 votes

# Answer
# Octave, ~~21~~ 20 bytes

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

```
> 2 votes

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

```
> 2 votes

# Answer
# 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.
> 2 votes

# Answer
# 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>
```
> 2 votes

# Answer
## 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.
> 2 votes

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

```
> 2 votes

# Answer
## Jelly, 3 bytes

```
ÆDL

```

Uses the builtin for divisors.
> 2 votes

# Answer
# 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
> 2 votes

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

```
> 2 votes

# Answer
# Japt, 3 bytes

```
â l

```

`-m` flag is for running all the test cases.

Try it
> 2 votes

# Answer
# 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.
> 2 votes

# Answer
# 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!
> 2 votes

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

```
> 2 votes

# Answer
# 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.
> 2 votes

# Answer
# JavaScript, ~~32~~30 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`.
> 2 votes

# Answer
# 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.
> 2 votes

# Answer
# Desmos, 30 bytes

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

```

Alternatively:

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

```

View them online
> 2 votes

# Answer
# Stax, 3 bytes

```
:d%

```

Run and debug it

It's the same size when packed.
> 2 votes

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

```
> 2 votes

# Answer
# 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.
> 2 votes

# Answer
# 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)
> 2 votes

# Answer
# Add++, ~~32~~ 29 bytes

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

```

Try it online!

## Explained (old)

```
x:?             # Set x to the input
Fx,             # For i in range(x):
    `r,         #       Set the active variable r AND
    x%i,        #       Assign to it the result of x%i
    r=0,        #       And then the result of r==0
    Ir,,        #       If r == 1:
        `y,,    #           Set the active variable to y AND
        y+1     #           Assign to it y + 1
Oy              # Output variable y

```
> 2 votes

# Answer
## Mathematica, 16 bytes

```
Length@*Divisors

```

Simple function composition of built-ins.
> 1 votes

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

```
> 1 votes

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

```
> 1 votes

# Answer
# 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`.
> 1 votes

# Answer
# O, 21 bytes

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

```

Sample run:

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

```
> 1 votes

# Answer
## 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.
> 1 votes

# Answer
# JavaScript (ES6), 29 bytes

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

```

Recursive solution.
> 1 votes

# Answer
# MY (noncompeting), 4 bytes

Hex:

```
1A 3A 47 27

```

Explanation:

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

```
> 1 votes

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

```
> 1 votes

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

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

```

Try it online!
> 1 votes

# Answer
# Perl 5, 21 bytes

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

```

Try it online!
> 1 votes

# Answer
# Knight, 31 bytes

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

```

Try it online!

`;` go brrrrr

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

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

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

```
> 1 votes

# Answer
# Vyxal, 2 bytes

```
KL

```

Try it Online!
> 1 votes

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

```
> 0 votes

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

```
> 0 votes

# Answer
# 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.
> 0 votes

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

```
> 0 votes

# Answer
## 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.
> 0 votes

# Answer
# 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.
> 0 votes

# Answer
# 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.
> 0 votes

# Answer
# , ~~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

```
> 0 votes

# Answer
# 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
> 0 votes

# Answer
# 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.
> 0 votes

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

```
> 0 votes

# Answer
# 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!
> 0 votes

# Answer
# Scala, ~~59~~ ~~61~~ 57 bytes

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

```
> 0 votes

# Answer
# Thunno 2 `L`, 1 byte

```
F

```

Attempt This Online!

Or **2 bytes** flagless:

```
Fl

```

Attempt This Online!

`F` gets the list of all factors, and `l` gets the length.
> 0 votes

---
Tags: code-golf, math, number-theory, division
---


title: Trim the array!

text:
# Question
Title: Trim the array!
Given an integer array and two numbers as input, remove a certain amount of the first and last elements, specified by the numbers. The input can be in any order you want.

You should remove the first *x* elements, where *x* is the first numerical input, and also remove the last *y* elements, where *y* is the second numerical input.

The resulting array is guaranteed to have a length of at least two.

## Examples:

```
[1 2 3 4 5 6] 2 1 -> [3 4 5]
[6 2 4 3 5 1 3] 5 0 -> [1 3]
[1 2] 0 0 -> [1 2]

```

# Answer
> 15 votes
# Haskell, ~~55~~ ~~39~~ ~~33~~ 29 bytes

*Saved 16 bytes thanks to Laikoni*

*Saved 6 more bytes thanks to Laikoni*

*Saved 4 more bytes thanks to Laikoni*

Am sure this could be improved, but as a beginner, gave it my best shot.

```
r=(reverse.).drop
a#b=r b.r a

```

## Usage

```
(5#0) [6,5,4,3,2,1,3]

```

Try it online!

# Answer
> 6 votes
# Mathematica, 17 bytes

```
#[[#2+1;;-#3-1]]&

```

**input**

> \[{1, 2, 3, 4, 5, 6}, 2, 1\]

# Answer
> 6 votes
# Octave, 20 bytes

```
@(a,x,y)a(x+1:end-y)

```

Try it online!

# Answer
> 5 votes
# Python, ~~28~~ 26 bytes

*-2 bytes thanks to @Rod*

```
lambda a,n,m:a[n:len(a)-m]

```

Try it online!

# Answer
> 5 votes
# C# (.NET Core), 55 54 bytes

```
using System.Linq;(a,x,y)=>a.Skip(x).Take(a.Count-x-y)

```

Try it online!

Uses a `List<int>` as input.

* 1 byte saved thanks to TheLethalCoder!

# Answer
> 5 votes
# Neim, 3 bytes

Try it here

Thanks to Okx for encouraging me to do this...:)

# Answer
> 5 votes
# Java (OpenJDK 8), 32 bytes

```
(l,i,j)->l.subList(i,l.size()-j)

```

Try it online!

If we really restrict to arrays, then it's 53 bytes:

```
(a,i,j)->java.util.Arrays.copyOfRange(a,i,a.length-j)

```

Try it online!

# Answer
> 4 votes
# Perl 5, 21 bytes

19 bytes of code + `-ap` flags.

```
$_="@F[<>..$#F-<>]"

```

Try it online!

Uses `-a` to autosplit the input inside `@F`, then only keep a slice of it according to the other inputs: from index `<>` (second input) to index `$#F-<>` (size of the array minus third input). And `$_` is implicitly printed thanks to `-p` flag.

# Answer
> 4 votes
## JavaScript (ES6), 27 bytes

```
(a,n,m)=>a.slice(n,-m||1/m)

```

A negative second parameter to `slice` stops slicing `m` from the end, however when `m` is zero we have to pass a placeholder (`Infinity` here, although `(a,n,m,o)=>a.slice(n,-m||o)` also works).

# Answer
> 4 votes
## Rust, 29 bytes

```
|n,i,j|&n[i..<[_]>::len(n)-j]

```

Call it as follows:

```
let a = &[1, 2, 3, 4, 5, 6];
let f = |n,i,j|&n[i..<[_]>::len(n)-j];
f(a, 2, 1)

```

I had a lot of fun fighting with the borrow checker figuring out what the shortest approach was in order to have it infer the lifetime of a returned slice. Its behavior around closures is somewhat erratic, as it will infer the lifetimes, but only if you do not actually declare the parameter as a reference type. Unfortunately this conflicts with being required to define the argument type in the signature as the n.len method call needs to know the type it's operating on.

Other approaches I tried working around this issue:

```
fn f<T>(n:&[T],i:usize,j:usize)->&[T]{&n[i..n.len()-j]}     // full function, elided lifetimes
let f:for<'a>fn(&'a[_],_,_)->&'a[_]=|n,i,j|&n[i..n.len()-j] // type annotation only for lifetimes. Currently in beta.
|n:&[_],i,j|n[i..n.len()-j].to_vec()                        // returns an owned value
|n,i,j|&(n as&[_])[i..(n as&[_]).len()-j]                   // casts to determine the type
|n,i,j|&(n:&[_])[i..n.len()-j]                              // type ascription (unstable feature)
|n,i,j|{let b:&[_]=n;&b[i..b.len()-j]}                      // re-assignment to declare the type

```

# Answer
> 4 votes
# TIS-100, ~~413~~ 405 Bytes

472 cycles, 5 nodes, 35 lines of code

```
m4,6
@0
MOV 0 ANY
S:MOV UP ACC
JEZ A
MOV ACC ANY
JMP S
A:MOV RIGHT ACC
L:JEZ B
MOV DOWN NIL
SUB 1
JMP L
B:MOV 0 RIGHT
MOV RIGHT NIL
@1
MOV RIGHT LEFT
MOV LEFT DOWN
MOV RIGHT DOWN
MOV DOWN LEFT
@2
MOV UP ACC
MOV UP LEFT
MOV ACC LEFT
@4
MOV 0 RIGHT
MOV UP NIL
S:MOV LEFT ACC
JEZ A
MOV ACC RIGHT
JMP S
A:MOV UP ACC
L:JEZ B
MOV RIGHT NIL
SUB 1
JMP L
B:MOV 0 UP
K:MOV RIGHT ACC
MOV ACC DOWN
JNZ K
@7
MOV UP ANY

```

The m4,6 at the top is not part of the code, but signals the placement of the memory modules.

Play this level yourself by pasting this into the game:

```

function get_name()
    return "ARRAY TRIMMER"
end
function get_description()
    return { "RECIEVE AN ARRAY FROM IN.A", "RECIEVE TWO VALUES A THEN B FROM IN.T", "REMOVE THE FIRST A TERMS AND LAST B TERMS FROM IN.A", "ARRAYS ARE 0 TERMINATED" }
end

function get_streams()
    input = {}
    trim = {}
    output = {}

  arrayLengths = {}

    a = math.random(1,5) - 3

    b = math.random(1,7) - 4

    arrayLengths[1] = 9+a
    arrayLengths[2] = 9+b
    arrayLengths[3] = 8-a
    arrayLengths[4] = 9-b

    s = 0

    trimIndex = 1

  for i = 1,4 do
      for k = 1,arrayLengths[i] do
          x = math.random(1,999)
      input[k+s] = x
            output[k+s] = x
        end

        input[s + arrayLengths[i] + 1]= 0
        output[s + arrayLengths[i] + 1]= 0

        a = math.random(0,3)
        b = math.random(0,arrayLengths[i]-a)

        trim[trimIndex] = a
        trim[trimIndex+1] = b

        trimIndex = trimIndex + 2

    s = s + arrayLengths[i] + 1
    end

    s = 1
    trimIndex = 1

    for i = 1,4 do

      for i = s,s+trim[trimIndex]-1 do
          output[i]=-99
        end

        for i = s + arrayLengths[i] - trim[trimIndex+1], s + arrayLengths[i]-1 do
      output[i]=-99
        end

  trimIndex = trimIndex +2
  s = s + arrayLengths[i] + 1
    end

    trimmedOut = {}
    for i = 1,39 do
            if(output[i] ~= -99) then
                    table.insert(trimmedOut, output[i])
            end
    end

    return {
        { STREAM_INPUT, "IN.A", 0, input },
        { STREAM_INPUT, "IN.T", 2, trim },
        { STREAM_OUTPUT, "OUT.A", 1, trimmedOut },
    }
end
function get_layout()
    return {
        TILE_COMPUTE,   TILE_COMPUTE,   TILE_COMPUTE,   TILE_COMPUTE,
        TILE_MEMORY,    TILE_COMPUTE,    TILE_MEMORY,   TILE_COMPUTE,
        TILE_COMPUTE,   TILE_COMPUTE,   TILE_COMPUTE,   TILE_COMPUTE,
    }
end

```

So I suppose this also counts as a lua answer...

# Answer
> 4 votes
# MATL, 6 bytes

```
QJi-h)

```

Try it online!

Input is given as 1) number of elements to trim from the start; 2) number of elements to trim from the end; 3) array. Explanation

```
Q   % Implicit input (1). Increment by 1, since MATL indexing is 1-based.
Ji- % Complex 1i minus real input (2). In MATL, the end of the array is given by `1i`.
h   % Concatenate indices to get range-based indexing 1+(1):end-(2).
)   % Index into (implicitly taken) input array. Implicit display.

```

# Answer
> 4 votes
# Husk, 3 bytes

```
↓↓_

```

Try it online!

### Explanation

```
                                               |  1 [1,2,3,4,5,6] 2
  _  -- negate y                               | -1 [1,2,3,4,5,6] 2
 ↓   -- drop y from end (negative argument)    |  [1,2,3,4,5] 2
↓    -- drop x from beginning                  |  [3,4,5]

```

# Answer
> 3 votes
# C#, 62 bytes

```
using System.Linq;(l,x,y)=>l.Where((n,i)=>i>=x&i<=l.Count-y-1)

```

Takes a `List<int>` as input and returns an `IEnumerable<int>`.

---

This also works for 64 bytes:

```
using System.Linq;(l,x,y)=>l.Skip(x).Reverse().Skip(y).Reverse()

```

# Answer
> 3 votes
# MATL, 10 bytes

```
tniQwi-&:)

```

Try it online!

## Explanation:

It's a bit long for just 11 bytes, but I'm writing it out in detail, to learn it myself too.

```
---- Input ----
[1 2 3 4 5 6]
2
1
----- Code ----
           % Implicit first input
t          % Duplicate input.
           % Stack: [1 2 3 4 5 6], [1 2 3 4 5 6]
 n         % Number of elements
           % Stack: [1 2 3 4 5 6], 6
  i        % Second input
           % Stack: [1 2 3 4 5 6], 6, 2
   Q       % Increment: [1 2 3 4 5 6], 6, 3
    w      % Swap last two elements
           % Stack: [1 2 3 4 5 6], 3, 6
     i     % Third input
           % Stack: [1 2 3 4 5 6], 3, 6, 1
      -    % Subtract
           % Stack: [1 2 3 4 5 6], 3, 5
       &:  % Range with two input arguments, [3 4 5]
           % Stack: [1 2 3 4 5 6], [3 4 5]
         ) % Use as index
           % Stack: [3 4 5]
           % Implicit display

```

# Answer
> 2 votes
# Jelly, 5 bytes

```
Ṗ¡Ḋ⁴¡

```

Try it online!

# Answer
> 2 votes
# Dyalog APL, 16 bytes

```
{(⍵↓⍨⊃⍺)↓⍨-⍺[2]}

```

Try it online!

# Answer
> 2 votes
# , ~~32~~ ~~31~~ 30 bytes

*-1 byte thanks to Rift*

*-1 byte thanks to Jarko Dubbeldam*

```
pryr::f(n[(1+l):(sum(n|1)-r)])

```

Evaluates to an anonymous function:

```
function (l, n, r)
    n[(1 + l):(sum(n|1) - r)]

```

`1+l` is necessary since R has 1-based indexing. `sum(n|1)` is equivalent to `length(n)` but it's a byte shorter.

Try it online!

# Answer
> 2 votes
# C++, ~~96~~ 95 bytes

*Thanks to @Tas for saving a byte!*

```
#import<list>
int f(std::list<int>&l,int x,int y){for(l.resize(l.size()-y);x--;)l.pop_front();}

```

Try it online!

# C++ (MinGW), 91 bytes

```
#import<list>
f(std::list<int>&l,int x,int y){for(l.resize(l.size()-y);x--;)l.pop_front();}

```

# Answer
> 2 votes
# APL (Dyalog), ~~8~~ 7 bytes

```
⌽⎕↓⌽⎕↓⎕

```

Try it online!

This takes the array as the first input, followed by the two numbers separately.

### Explanation

```
⎕            from the input array
⎕↓           drop the first input elements
⌽            reverse the array
⎕↓           drop first input elements
⌽            reverse again to go back to the original array

```

# Answer
> 2 votes
# PHP\>=7.1, 59 bytes

```
<?[$a,$b,$e]=$_GET;print_r(array_slice($a,$b,$e?-$e:NULL));

```

PHP Sandbox Online

# Answer
> 2 votes
# Brain-Flak, 60 bytes

```
(()()){({}<{({}<{}>[()])}{}([]){{}({}<>)<>([])}{}<>>[()])}{}

```

Try it online!

Input is in this format:

```
x

a
r
r
a
y

y

```

Where `x` is the number to take from the front, `y` is the number to take from the back, and the array is just however many numbers you want, separated by newlines. Here are my first two (longer) attempts:

```
({}<>)<>{({}<{}>[()])}([])<>({}<><{{}({}<>)<>([])}{}><>){({}<{}>[()])}{}([]){{}({}<>)<>([])}<>{}
{({}<{}>[()])}{}([]){{}({}<>)<>([])}{}<>{({}<{}>[()])}{}([]){{}({}<>)<>([])}<>

```

And here is an explanation:

```
#Two times:
(()()){({}<

    #Remove *n* numbers from the top of the stack
    {({}<{}>[()])}{}

    #Reverse the whole stack
    ([]){{}({}<>)<>([])}{}<>

>)[()]}{}

```

# Answer
> 2 votes
# C++, ~~50~~ ~~48~~ 46 bytes

```
#define f(a,x,y)decltype(a)(&a[x],&*a.end()-y)

```

Try it online!

# Answer
> 2 votes
# APL (Dyalog), 5 bytes

```
(⌽↓)/

```

Try it online!

---

Input format is `y x A`

**Explanation**

`/` is Reduce, which inserts the function to the left between each pair of elements of the argument

`(⌽↓)` is a function train equivalent to `{⌽⍺↓⍵}`, which removes the first  elements of the array  and then reverses the array. ( is the left argument and  is the right argument)

Thus, `(⌽↓)/y x A` is equivalent to `⌽y↓⌽x↓A`, which is what is needed.

# Answer
> 2 votes
# Ruby, 17 bytes

```
->a,b,c{a[b..~c]}

```

Try it online!

# Answer
> 2 votes
# Japt, 6 bytes

```
oW UsV

```

Try it

```
sVWnUl

```

Try it

```
oW UsV     :Implicit input of array U and integers V=x & W=y
oW         :Remove the last W elements of U, mutating the original
   UsV     :Slice U from 0-based index V

```

```
sVWnUÊ     :Implicit input of array U and integers V=x & W=y
sV         :Slice U from 0-based index V to index
  Wn       :  Subtract W from
    UÊ     :  Length of U

```

# Answer
> 2 votes
# Kotlin, 30 bytes

```
{a,s,e->a.drop(s).dropLast(e)}

```

Try it online!

Takes `List<Int>` as input and drops from begin and then from end.

# Answer
> 2 votes
# Brachylog, ~~11~~ 10 bytes

```
kb₍B&t;Bk₍

```

Try it online!

Takes input as \[x, A, y\] where A is the array to trim.

*(-1 byte thanks to @Fatalize.)*

# Answer
> 2 votes
# K (oK), 10 bytes

```
{(-z)_y_x}

```

Try it online!

Port of my q/kdb+ answer...

# Answer
> 1 votes
# 05AB1E, 6 bytes

```
F¦}sF¨

```

Try it online!

```
F }    # For 0 .. number of elements to remove from front
 ¦     #   Remove the first element
   s   # Get the next input
    F  # For 0 .. number of elements to remove from back
     ¨ #   Remove the last element

```

# Answer
> 1 votes
# Pyth, 5 bytes

```
>E<QE

```

Try it here

Takes the arguments in the opposite order. `<` and `>` in Pyth trim based on argument order. For example, `<Q5` will trim off all values in the input after the fifth one.

# Answer
> 1 votes
# Java 8, 82 bytes

```
a->n->m->{int l=a.length-m-n,r[]=new int[l];System.arraycopy(a,n,r,0,l);return r;}

```

Try it here.

Alternative with same (**82**) byte-count using a loop:

```
(a,n,m)->{int l=a.length-m,r[]=new int[l-n],i=0;for(;n<l;r[i++]=a[n++]);return r;}

```

Try it here.

**Explanation:**

```
a->n->m->{                      // Method with integer-array and two integer parameters and integer-array return-type
  int l=a.length-m-n,           //  Length of the array minus the two integers
      r[]=new int[l];           //  Result integer-array
  System.arraycopy(a,n,r,0,l);  //  Java built-in to copy part of an array to another array
  return r;                     //  Return result-String
}                               // End of method

```

`System.arraycopy`:

> `arraycopy(Object src, int srcPos, Object dest, int destPos, int length)`:
>
> The `java.lang.System.arraycopy()` method copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. A subsequence of array components are copied from the source array referenced by `src` to the destination array referenced by `dest`. The number of components copied is equal to the `length` argument.
>
> The components at positions `srcPos` through `srcPos + length - 1` in the source array are copied into positions `destPos` through `destPos + length - 1`, respectively, of the destination array.

# Answer
> 1 votes
# CJam, 8 bytes

```
{_,@-<>}

```

Anonymous block that takes the inputs from the stack in the order *x*, *y*, array, and replaces them by the output array.

**Try it online!**

### Explanation

Consider inputs `2`, `1`, `[10 20 30 40 50 60]`.

```
{      }    e# Block
            e# STACK: 2, 1, [10 20 30 40 50 60]
 _          e# Duplicate
            e# STACK: 2, 1, [10 20 30 40 50 60], [10 20 30 40 50 60]
  ,         e# Length
            e# STACK: 2, 1, [10 20 30 40 50 60], 6
   @        e# Rotate
            e# STACK: 2, [10 20 30 40 50 60], 6, 1
    -       e# Subtract
            e# STACK: 2, [10 20 30 40 50 60], 5
     <      e# Slice before
            e# STACK: 2, [10 20 30 40 50]
      >     e# Slice after
            e# STACK: [30 40 50]

```

# Answer
> 1 votes
# tcl, 19

```
lrange $L $x end-$y

```

where `L` is the array.

# demo

# Answer
> 1 votes
# q/kdb, 12 bytes

**Solution:**

```
{(0-z)_y _x}

```

**Example:**

```
q){(0-z)_y _x}[1 2 3 4 5 6;2;1]
3 4 5
q){(0-z)_y _x}[6 2 4 3 5 1 3;5;0]
1 3
q){(0-z)_y _x}[1 2;0;0]
1 2

```

**Explanation:**

```
{          } / lambda function
          x  / input array
       y _   / drop y elements from .. (takes from start)
 (0-z)       / negative z ()
      _      / drop -z elements from ... (takes from end)

```

# Answer
> 1 votes
# Racket, 33 bytes

```
(λ(a i j)(drop-right(drop a i)j))

```

It can be called like so:

```
((λ(a i j)(drop-right(drop a i)j)) '(1 2 3 4 5 6) 2 1)

```

# Answer
> 1 votes
# Pyth, 4 bytes

```
<E>E

```

Demonstration

Put the list last.

# Answer
> 1 votes
# Kona/K4, 12 bytes

```
{x _(-y)_ z}

```

Usage:

```
   {x _(-y)_ z}[2;1;"hello world"]
"llo worl"

```

# Answer
> 1 votes
# C (gcc), 16 bytes

The compiler instruction:

```
-DX(a,x,y)=(a+x)
```

As most would know, an array in C is just a known length and a pointer to the beginning of an array. Thus, we get an array with `x` members removed from the left and `y` members removed from the right by just moving the pointer to the array by `+x`.

Try it online!

# Answer
> 1 votes
# Jelly, 5 bytes

```
‘ṫṚ¥ƒ

```

Try it online!

Takes `[x, y]` on the left and the list on the right. Ties the existing Jelly answer, but I'm posting it anyways because:

* it doesn't use full-program I/O
* it feels like it *should* be four bytes

```
‘        Increment x and y.
    ƒ    With the list as the initial value of the accumulator, reduce [x, y] by:
 ṫ       remove the first (right - 1) elements from the accumulator,
  Ṛ¥     then reverse it.

```

# Answer
> 1 votes
# Jellyfish, 19 bytes

```
p
vvj
 -0
 j
 0
j
0

```

Try it online!

Takes input as

```
y
array
x

```

via STDIN.

This program translates to:

```
p    (v   (j         (0),v   (-    (0,j         (0)),j         (0)))
print(drop(eval_input(0),drop(minus(0,eval_input(0)),eval_input(0)))

```

# Answer
> 1 votes
# Julia, 18 bytes

```
a*b*c=a[1+b:end-c]

```

Try it online!

# Answer
> 1 votes
# Excel, 32 bytes

```
=OFFSET(A1,B1,,COUNT(A:A)-B1-C1)

```

Link the Spreadsheet

The array is entered in column A starting at A1.

# Answer
> 1 votes
# Vyxal, 3 bytes

```
N"i

```

Try it Online!

# Answer
> 1 votes
# Go, 49 bytes, `int`s only

```
func f(t[]int,x,y int)[]int{return t[x:len(t)-y]}

```

Attempt This Online!

# Go, 52 bytes, generic

```
func f[T any](t[]T,x,y int)[]T{return t[x:len(t)-y]}

```

Attempt This Online!

# Answer
> 1 votes
# Thunno, \\$5\log\_{256}(96)\approx\\$ 4.12 bytes

```
ZxsZy

```

Attempt This Online!

Takes `x` then the array then `y`

#### Explanation

```
Zx     # Remove the first x elements from the array
  s    # Swap so y is now on the top of the stack
   Zy  # Remove the last y elements from the array
       # Implicit output

```

# Answer
> 1 votes
# Elm, 44 bytes

```
h x=List.reverse<<List.drop x
f x y=h y<<h x

```

Try it on Ellie

# Answer
> 0 votes
# Japt, 8 7 bytes

```
sVUl -W

```

Try it online!

Saved a byte thanks to ETHproductions

# Answer
> 0 votes
# , ~~9~~ 8 bytes

```
ÀñdñGÀñd

```

Try it online!

One byte saved thanks to Erik the golfer!

# Answer
> 0 votes
## Clojure, 28 bytes

```
#(subvec % %2(-(count %)%3))

```

Well there is the built-in.

# Answer
> 0 votes
# NewStack, 5 bytes

```
ᵢqᵢpᵢ

```

The symmetry is an amazing coincidence

## The breakdown:

```
ᵢ      Append an input (the array).
 qᵢ    Pop off an input's amount off the bottom.
   pᵢ  Pop off an input's amount off the top.

```

# Answer
> 0 votes
# F#, 39 bytes

```
let f(i:int[])s e=i.[s..(i.Length-1-e)]

```

Try it online!

# Answer
> 0 votes
# Braingolf, ~~22~~ 21 bytes

```
1-<1-[v$_R][v<$_R]v=;

```

Try it online!

# Answer
> 0 votes
## LOGO, 33 bytes

```
[cascade ?2 "bf cascade ?3 "bl ?]

```

Try it on FMSLogo.

This is a `template-list` in LOGO, which is the equivalent of lambda (anonymous) function in many other languages.

Where:

* `cascade` outputs the result of applying a template repeatedly, in this case is `?2` times `bf` and `?3` times `bl`.
* `bf` and `bl` stands for `ButFirst` and `ButLast` respectively.
* `?` is used to access parameters. So `?2` is the second parameter, `?3` is the third parameter, etc.

Test:

```
show apply [cascade ?2 "bf cascade ?3 "bl ?] [[1 2 3 4 5 6] 2 1]

```

print `[3 4 5]`.

# Answer
> 0 votes
# Clojure, 26 bytes

```
#(drop %2(drop-last %3 %))

```

# Answer
> 0 votes
# Perl 6, 18 bytes

```
{@^a[$^x..^*-$^y]}

```

`@^a` is the input array (first parameter), `$^x` is the number of elements to remove from the front (second parameter), and `$^y` is the number of elements to remove from the end (third parameter).

`$^x ..^ *-$^y` is a slicing subscript that selects a range of elements from the one with index `$^x` until one prior to the one with index `*-$^y` (`*` meaning "the length of the array" in a subscript context).

# Answer
> 0 votes
# C++, 81 bytes

```
#include<vector>
int f(std::vector<int>&v,int x,int y){v={v.begin()+x,v.end()-y};}

```

Not as short as this use of a macro.

`std::vector` provides random access, and we simply create a new `vector` from the start point `v.begin()` \+ `x`, to the new end point `v.end()` \- `y` elements.

Uses the iterator overload `v.begin()` and `v.end()` since it's the same length as the pointer one `&v[0]` and `&*(v.end())`, but more readable.

Function doesn't return an `int` like it promises, which is only a compiler warning.

# Answer
> 0 votes
# 8th, 33 bytes

**Code**

This code leaves resulting array on TOS

```
( a:rev swap -1 a:slice ) 2 times

```

**Usage**

```
ok> 2 1 [1,2,3,4,5] ( a:rev swap -1 a:slice ) 2 times .
[3,4]
ok> 5 0 [6,2,4,3,5,1,3] ( a:rev swap -1 a:slice ) 2 times .
[1,3]
ok>
ok> 0 0 [1,2] ( a:rev swap -1 a:slice ) 2 times .
[1,2]
ok>

```

# Answer
> 0 votes
# Common Lisp, 41 bytes

```
(lambda(a x y)(subseq a x(-(length a)y)))

```

Try it online!

# Answer
> 0 votes
# J, 17 bytes

```
(-@{:@[}.{.@[}.])

```

Usage:

```
   2 1 (-@{:@[}.{.@[}.]) 11 12 13 14 15 16
13 14 15

```

# Answer
> 0 votes
# C++, 50 bytes

```
[](auto&v,int x,int y){v={v.begin()+x,v.end()-y};}

```

Just construct a new container from the existing one. This requires `v` to be of a type with random-access iterators and constructible from an iterator pair - `std::vector` is ideally suited.

## Demo

```
auto const trim =
    [](auto&v,int x,int y){v={v.begin()+x,v.end()-y};}
    ;

#include<iostream>
#include<vector>
int main(int argc, char **argv)
{
    if (argc < 4) {
        std::cerr << "Usage: " << argv[0] << " X Y ELE...";
        return 1;
    }

    auto const x = std::atoi(argv[1]);
    auto const y = std::atoi(argv[2]);
    std::vector<int> v;
    v.reserve(argc - 3);
    for (int i = 3;  i < argc;  ++i)
        v.push_back(std::atoi(argv[i]));

    auto const print_vector = [](auto v){for(auto i:v)std::cout<<i<<" ";std::cout<<'\n';};

    print_vector(v);
    trim(v, x, y);
    print_vector(v);
}

```

# Answer
> 0 votes
# Scala, 52 bytes

```
def f(a:Seq[Int],c:Int,d:Int)=a.dropRight(d).drop(c)

```

Try it online!

# Answer
> 0 votes
# Lua, 94 bytes

```
n,s=loadstring('return{},'..p[1])()for x=1,#s do n[#n+1]=x>0+p[2]and#s>=x+p[3]and s[x]or _ end

```

Try it online!

If I used something that I couldn't please tell me.

### Explanation

```
p = {...} -- (Header) It gets the 3 arguments (the list and the 2 numbers and stores in a table)

n,s=loadstring('return{},'..p[1])() -- is the same as (i) and (ii):
 (i) n = {} -- initializes an empty table
(ii) s = loadstring('return '..p[1])() -- makes the string '{1,2,3}' become a table with 3 elements (1, 2 and 3)

for x=1,#s do -- from 1 to the number of elements in s, repeat:
  n[#n+1] = x>0+p[2] and #s>=x+p[3] and s[x] or _
  n[#n+1]   -- append to n
              0+p[2]   -- convert "2" to the number 2
            x>0+p[2] and #s>=x+p[3]   -- if we're past the start limit and before the end limit
                                    and s[x]   -- then the element to be appended is the one with index x of the original list
                                             or _   -- else append nil (the same as doing nothing)
end

print(table.concat(n, ", ")) -- (Footer) print the elements of n separated by commas

```

I used _ as nil just to be a little bit more clear (although this is not the point of these answers hahah). I could've used any variable that wasn't previously declared. `_` doesn't have anything special in Lua.
And the comparisons are really messy because I tried to organize the math in a way that special characters would help me to use less space. `... and a>#b` uses 1 more byte than `... and#b>a`.

If you have any questions ask and I'll try to answer them.

# Answer
> 0 votes
# Recursiva, 7 bytes

```
Zba-Lac

```

Try it online!

# Answer
> 0 votes
# Factor, 19 bytes

```
[ head* swap tail ]

```

Try it online!

Takes input as `x sequence y`.

# Answer
> 0 votes
# Arturo, 31 bytes

```
$[a,x,y][slice a x(size a)-y+1]

```

Try it

# Answer
> 0 votes
# Zsh, 21 bytes

```
<<<${@:2+$1:-1-$@[#]}

```

Try it online!

Input format: `x` `<array>` `y`

# Answer
> 0 votes
# Thunno 2, 2 bytes

```
ỵẓ

```

Attempt This Online!

Input in the order \\$a, l, b\\$, where \\$a\\$ is the number of items to remove from the front, \\$b\\$ is the number of items to remove from the back, and \\$l\\$ is the list.

#### Explanation

```
ỵẓ  # Implicit input
ỵ   # Remove from front
 ẓ  # Remove from back
    # Implicit output

```

---
Tags: code-golf, array
---


title: What's the Date?

text:
# Question
Title: What's the Date?
## Challenge

Weirdly, this hasn't been done yet: output the current date.

## Rules

The date format you should follow is as follows:

```
YYYY-MM-DD

```

Where the month and day should be padded by zeroes if they are less than 10.

For example, if the program is run on the 24th May 2017, it should output

```
2017-05-24

```

The date can either be always in UTC or in the local date.

You must handle leaps years. i.e. in leap years, February has 29 days but 28 days in a normal year.

## Winning

Shortest code in bytes wins.

# Answer
# Bash with GNU coreutils, ~~16~~ 7 bytes

-8 bytes thanks to Neil (and fergusq) (no pipe required to output)
-1 byte thanks to 12431234123412341234123 (use the built-in option with flag `-I`!)

```
date -I

```

**Try it online!**
> 12 votes

# Answer
# PHP, 17 bytes

```
<?=date('Y-m-d');

```
> 10 votes

# Answer
# Bash, 15 bytes

```
printf '%(%F)T'

```

Sample run:

```
bash-4.4$ printf '%(%F)T'
2017-05-24

```

Try it online!
> 7 votes

# Answer
# Japt, 6 bytes

```
Ks3 ¯A

```

Try it online!

## Explanation:

```
Ks3 ¯A
K       // New Date()
 s3     // .toISOString()
    ¯A  // .slice(0,10)

```
> 7 votes

# Answer
## JavaScript (ES6), 34 bytes

```
_=>new Date().toJSON().split`T`[0]

```

```
f=

_=>new Date().toJSON().split`T`[0]

console.log(f());
```
> 5 votes

# Answer
# SQLite, 13 characters

```
select date()

```

Good boy, SQLite. Other SQL dialects usually need either `current_date` or `date(now())`.

Sample run:

```
bash-4.4$ sqlite3 <<< 'select date()'
2017-05-24

```
> 4 votes

# Answer
## Mathematica, 20 bytes

```
DateString@"ISODate"

```
> 4 votes

# Answer
# Perl 6,  ~~14~~  12 bytes

```
Date.today.say

```

Try it

```
now.Date.say

```

Try it
> 4 votes

# Answer
# Excel, 24 bytes

```
=TEXT(NOW(),"yyy-mm-dd")

```

Excel will still do a 4-digit year with only 3 `y`'s.
> 3 votes

# Answer
# , 10 bytes

```
Sys.Date()

```

Try it online!
> 2 votes

# Answer
# jq, 19 characters

(15 characters code + 4 characters command line options)

```
now|todate[:10]

```

Sample run:

```
bash-4.4$ jq -nr 'now|todate[:10]'
2017-05-24

```

Try in jq‣play
> 2 votes

# Answer
# Lua, 18 characters

```
print(os.date"%F")

```

Sample run:

```
bash-4.4$ lua -e 'print(os.date"%F")'
2017-05-24

```

Try it online!
> 2 votes

# Answer
## Alice, 9 bytes

```
/oT\
@%;'

```

Try it online!

### Explanation

I'll leave the exact control flow as an exercise to the reader, but the linearised code that is being run in Ordinal mode is:

```
%T'T%;o@

```

And here is what it does:

```
%   Split an implicit empty string around an implicit empty string. Really doesn't
    do anything at all.
T   Push the current datetime as a string like "2017-05-24T20:53:08.150+00:00"
'T  Push "T".
%   Split the datetime string around the "T", to separate the date from the time.
;   Discard the time.
o   Output the date.
@   Terminate the program.

```

One way this might be golfable is to reuse the `%` to terminate the program in Cardinal mode with a division by zero, but the only layout I've come up with is the following:

```
\;T
\%o'

```

But here, the `%` doesn't actually terminate the program, because we push 111 (`'o`) right beforehand so there's never a division by zero.

In principle it might also be possible to reuse `%` to get rid of the `;`, since trying to split the date around the time will simply discard the time.
> 2 votes

# Answer
# VBA, 5 25 bytes

`?Date` *unpredictable, dependent on system short date settings*

```
?Format(Now,"yyyy-mm-dd")

```

### Output:

```
2017-05-25

```
> 2 votes

# Answer
# Java 8, ~~26~~ 32 bytes

```
()->java.time.LocalDate.now()+""

```

Fixed format thanks to Kevin Cruijssen
> 2 votes

# Answer
# SmileBASIC 3, 29 bytes

SB has a date string built in... but it's in the wrong format! It uses slashes instead of dashes, no good. Plus, being the self-respecting BASIC it is, there is no global replace function. I guess I have to do it myself...

```
D$=DATE$D$[4]="-
D$[7]="-
?D$

```
> 2 votes

# Answer
# Prolog (SWI), 46 bytes

```
f(X):-get_time(Y),format_time(atom(X),'%F',Y).

```

Try it online!
> 2 votes

# Answer
# x86-16 machine code, IBM PC DOS, ~~55~~ ~~53~~ 48 bytes

Binary:

```
00000000: b42a cd21 91b3 64f6 f38b c8e8 1400 8ac5  .*.!..d.........
00000010: e80f 00b0 2dcd 298a c6e8 0600 b02d cd29  ....-.)......-.)
00000020: 8ac2 d40a 0530 3050 86c4 cd29 58cd 29c3  .....00P...)X.).

```

Listing:

```
B4 2A       MOV  AH, 2AH        ; get system date: CX=year, DH=month, DL=day
CD 21       INT  21H            ; call DOS API
91          XCHG AX, CX         ; move year in CX to AX (dividend)
B3 64       MOV  BL, 100        ; divide by 100 to separate digits of year
F6 F3       DIV  BL             ; AL = first two digits, AH = last two digits
8B C8       MOV  CX, AX         ; save AX to CX to display last two digits later
E8 0122     CALL DISP_WORD      ; display decimal value in AL
8A C5       MOV  AL, CH         ; move last two digits to AL
E8 0122     CALL DISP_WORD      ; display decimal value in AL
B0 2D       MOV  AL, '-'        ; date separator
CD 29       INT  29H            ; fast write AL to screen
8A C6       MOV  AL, DH         ; move month in DH into AL for display
E8 0122     CALL DISP_WORD      ; display decimal value in AL
B0 2D       MOV  AL, '-'        ; date separator
CD 29       INT  29H            ; fast write AL to screen
8A C2       MOV  AL, DL         ; move day into AL and display
        DISP_WORD:
D4 0A       AAM                 ; convert binary to BCD
05 3030     ADD  AX, '00'       ; convert BCD to ASCII char
50          PUSH AX             ; save second digit for display later
86 C4       XCHG AL, AH         ; convert endian, AL = first digit, AH = second digit
CD 29       INT  29H            ; fast write AL to screen
58          POP  AX             ; restore digits
CD 29       INT  29H            ; fast write AL to screen
C3          RET                 ; return to caller/DOS

```

***Output***

Standalone DOS program, run from the command line outputs current date to the screen.

Much of this program is converting binary values to ASCII for console output. This uses (abuses) the binary-to-BCD instruction (`AAM`) to create a printable ASCII version of the output.
> 2 votes

# Answer
# Pyth, 19 bytes

`++++.d3"-".d4"-".d5`

In Pyth `.` allows you to access a number of extra syntactic goodies. `d` contains various date options which are accessed with `.d#`, where `#` is a number 0-9. `3` is for the current year, `4` is the current month, and `5` is for the current day.

Format for the challenge wants dashes between each element of the date so we append them. Pyth using Polish notation for all math operands, thus the `++++`.
> 2 votes

# Answer
# Factor, 21 bytes

```
[ now timestamp>ymd ]

```

Try it online!
> 2 votes

# Answer
# TI-Basic, 72 bytes

```
getDate→A
toString(Ans(1→B
toString(ʟA(2→C
toString(ʟA(3→D
If C<10
"0"+C→C
If D<10
"0"+D→D
B+"-"+C+"-"+D

```

This only works on a TI-84+ CE OS 5.2 and if the user has already set the time and date correctly.
> 2 votes

# Answer
# CJam, ~~22~~ 15 bytes

```
et3<{sY0e[}%'-*

```

Try it online!

-7 bytes thanks to Challenger5.

Explanation:

```
et                       Get array with [year,month,day,stuff...]
  3<                     Slice array to get [y,m,d]
    {                    For each item do:
     s                     To string
      Y0e[                 add a 0 to the beginning of the string if it is shorter than 2 chars.
          }%             End for each
            '-*          Join the array with "-" as a separator

```
> 1 votes

# Answer
# Crystal, 30 bytes  24 bytes  21 bytes

-6 thanks to Nick Clifford

-3 from looking at snail\_'s answer in Ruby

```
p Time.now.to_s("%F")

```

Try it online!
> 1 votes

# Answer
## QBIC, 33 bytes

```
B=_D?_sB,-4|+@-`+_sB,2|+A+_sB,4,2

```

Explanation:

```
B=_D        Assign the system's date to B$
            This is in American mm-dd-yyyy format, so we'll need to do some reformatting
?_sB,-4|    PRINT substring B, take 4 chars from the right
 +@-`         plus the string literal "-", now A$
 +_sB,2|      plus the leftmost two chars
 +A           and A$ again
 +_sB,4,2     plus the middle part.

```
> 1 votes

# Answer
# Python 2,  ~~53~~  40 bytes

-10 bytes thanks to Gábor Fekete (ISO-8601 is the default format for a date object)

```
from datetime import*
print date.today()

```

**Try it online!**

### How?

`datetime.date.today()` will return a `datetime.date` object containing the local date information.

`print` will print a string representation of that object, this will call the object's `__str__` function.

From the docs:

* `date.__str__()`: For a `date` `d`, `str(d)` is equivalent to `d.isoformat()`.
* `date.isoformat()`: Return a `string` representing the date in **ISO 8601** format, `‘YYYY-MM-DD’`. For example, `date(2002, 12, 4).isoformat() == '2002-12-04'`.
> 1 votes

# Answer
# Go, ~~62~~ 56 bytes

```
import."time"
func f()string{return Now().String()[:10]}

```

Try it online!
> 1 votes

# Answer
# q/kdb+, ~~18~~ 16 bytes

**Solution:**

```
ssr[.z.d$:].".-"

```

**Example:**

```
q)ssr[.z.d$:].".-"
"2018-01-01"

```

**Explanation:**

Take the string representation of today's date, and replace the dots with dashes.

```
ssr[string .z.d;".";"-"] / fully ungolfed solution
ssr[string .z.d;;].".-"  / partially ungolfed solution
           .z.d          / current UTC date (2018.01.01)
    string               / convert to string ("2018.01.01")
ssr[           ;;]       / string-search-replace
                  .".-"  / the two parameters

```
> 1 votes

# Answer
# Python 2, 40 bytes

```
from datetime import*;print date.today()

```
> 1 votes

# Answer
# Powershell, ~~26~~ 17 bytes

```
Date -f yyy-MM-dd

```

Thanks to @ConnorLSW for the 9 bytes.
> 1 votes

# Answer
# Oracle SQL, 46 bytes

```
SELECT TO_CHAR(SYSDATE,'YYYY-MM-DD') FROM DUAL

```
> 1 votes

# Answer
# 05AB1E, ~~16~~ 13 bytes

Saved 3 bytes thanks to *Kevin Cruijssen*

```
žgžfže)T‰J'-ý

```

Try it online!

**Explanation**

```
žgžfže)         # push [year, month, day]
       T‰       # divmod each by 10
         J      # join each div and mod result together
          '-ý   # join year-month-day on "-"

```
> 1 votes

# Answer
# C#, ~~46~~ 45 bytes

```
_=>System.DateTime.Now.ToString("yyy-MM-dd");

```

*Saved a byte thanks to @raznagul.*
> 1 votes

# Answer
# Ruby, 23 bytes

Prints the local time.

```
p Time.now.strftime'%F'

```
> 1 votes

# Answer
# MATLAB/Octave, ~~25~~ 15 bytes

```
datestr(now,29)

```

Try it online!

---

The built-in function `now` returns the current system date in a weirdy MATLAB serial format.

`datestr` formats the weirdy serial format into a string of a requested format - which is in this case `'YYYY-mm-dd'`. It turns out that MATLAB has a list of predefined formats for `datestr`. ISO8601 is one of them and is represented by the number 29, which allows a saving of 10 bytes.
> 1 votes

# Answer
# Rust, 84 Bytes

```
extern crate chrono;fn main(){print!("{}",chrono::Local::now().format("%Y-%m-%d"));}

```
> 1 votes

# Answer
# Noether, 8 bytes

```
6D0 10SP

```

**Try it here!**

***Explanation:***

```
6  - Push the number 6 onto the stack
D  - Pop the mode number off the top of the stack and push the ISO date string (Mode 6)
0  - Push the number 0 onto the stack
10 - Push the number 10 onto the stack
S  - Pop the three items, A, B and C off the top of the stack and slice the string, A, from B to C
P  - Print the item on the top of the stack

```

---

Alternatively, you could use the following method (also for 8 bytes):

```
6D"T"^#P

```

**Try it here!**

***Explanation:***

```
6   - Push 6 onto the stack
D   - Pop the mode number off the top of the stack and push the ISO date string (Mode 6)
"T" - Push the string "T" onto the stack
^   - Pop two strings A and B off the stack and split A by B
#   - Pop the top item off the stack
P   - Print the item on the top of the stack

```
> 1 votes

# Answer
### C++14, 143 bytes 139 bytes

```
#include <cstdio>
#include <time.h>
int main (){time_t t;char D[11];time(&t);strftime(D,sizeof D,"%Y-%m-%d",localtime(&t));printf("%s",D);}

```

Timtech pointed out to me that i don't need all spaces

Test me!
> 1 votes

# Answer
## Swift, 13 bytes

```
print(Date())

```
> 1 votes

# Answer
# , 16 bytes

```
6!:0'YYYY-MM-DD'

```

Try it online!
> 1 votes

# Answer
# vim, 18

```
i®=strftime("%F")↵

```

where *®* and  are *Ctrl-R* and *Enter*.
> 1 votes

# Answer
# Zsh, 15 bytes

Who needs `date`?

```
print -P %D{%F}

```

Try it online!

If we assume the program will only be run in current century, we can save 2 bytes:

```
print -P 20%D

```
> 1 votes

# Answer
# Perl 6, 12 bytes

```
say now.Date

```

Try it online!
> 1 votes

# Answer
# Vyxal, 2 bytes

```
kD

```

Try it Online!

Uh, it's a built in constant using python's `date.today().isoformat()`.
> 1 votes

# Answer
# Jelly, 45 bytes

```
“from datetime import*;print(date.today())”ŒV

```

Try it online!

evaluates python code because *comedy*
> 1 votes

# Answer
# Python 2, 59 bytes

Oddly enough, ~~I can't find an easier built-in...~~ somebody else found it. \>\<

```
from datetime import*
print datetime.now().isoformat()[:10]

```

Try it online!
> 0 votes

# Answer
# Fourier, 33 bytes

```
|~D<10{1}{0o}Do|F5do`-`4d^F`-`3dF

```

**Try it online!**

Uses a function which adds the leading zero... So long :P
> 0 votes

# Answer
# C, ~~104~~ ~~79~~ 61 bytes

Saved 18 bytes thanks to hvd.

```
n,b[99];f(){time(&n);strftime(b,99,"%F",gmtime(&n));puts(b);}

```
> 0 votes

# Answer
## SAS, 31 bytes

```
%put %sysfunc(date(),yymmdd10.);

```
> 0 votes

# Answer
# MATL, 6 bytes

```
Z'29XO

```

Try it online!

### Explanation

```
Z'    % Push current date and time as a float
29    % Push 29
XO    % String representation of date and time with specified format.
      % Format 29 corresponds to 'yyyy-mm-dd'. Implicitly display

```
> 0 votes

# Answer
# C#, 51 bytes

```
Console.Write(DateTime.Now.ToString("yyyy-MM-dd"));

```
> 0 votes

# Answer
# Pyth, 20 bytes

```
j\-+.d3m.[\02`.d+4d2

```

Try it here.
> 0 votes

# Answer
# VBA, 26 Bytes

Anonymous VBE Immediate window function that outputs the current date in the specified format, regardless of system settings, to the VBE immediate window

```
?Format(Now,"YYYY-MM-DD")

```
> 0 votes

# Answer
## Objective-C, 27 bytes

```
NSLog(@"%@",[NSDate date]);

```
> 0 votes

# Answer
# Windows batch, ~~166 144 136~~ 107 bytes

```
@set X=
@for /f "skip=1" %%x in ('wmic os get localdatetime')do @set X=%%x
@echo %X:~0,4%-%X:~4,2%-%X:~6,2%

```

Outputs local time
> 0 votes

# Answer
## PowerShell, 16 bytes

```
date -u %Y-%m-%d

```

Try it online!
> 0 votes

# Answer
# Haskell, 55 bytes

```
import Data.Time
m=getCurrentTime>>=putStr.take 10.show

```

Not exactly the shortest answer (even the Java answer is shorter!)

## Explanation

```
import Data.Time                            --put the function getCurrentTime into scope
m=getCurrentTime>>=putStr.take 10.show
m=                                          --define a variable/function m
  getCurrentTime                            --get the current time wrapped in the IO type
                >>=                         --feed the current time into the following function
                                  show      --display the time as a string
                          take 10.          --take the first ten characters of that to get the date
                   putStr.                  --print it

```
> 0 votes

# Answer
# Python, 39 bytes

Beats this answer by 1 byte.

```
from datetime import*;str(date.today())

```

This won't actually work when put in a file and executed, but it does work when you paste this in a python shell. However, it works if you have this in a file and then call that file's `__main__` function, so I don't know if this is allowed by the rules. I'm going to assume that it is.
> 0 votes

# Answer
# APL (Dyalog), 17 bytes

```
'-'@5 8⍕1E3⊥3↑⎕TS

```

Try it online!

`⎕TS` Y M D h m s ms

`3↑` take the first three

`1E3⊥` evaluate in base-1000

make into string

`'-'@5 8` substitute a dash at positions five and eight
> 0 votes

# Answer
# Common Lisp, 86 chars

```
(multiple-value-bind(a b c d e f)(get-decoded-time)(format t"~4a-~2,'0d-~2,'0d"f e d))

```

Good old verbose Common Lisp!

Try it online!
> 0 votes

# Answer
# Funky, 18 bytes

```
@os.date"%Y-%m-%d"

```

Try it online!
> 0 votes

# Answer
# AWK, 17 bytes

```
$0=strftime("%F")

```

Try it online!
> 0 votes

# Answer
# jamal, 32 characters

```
{@format date=YEAR-0M-0D}{@date}

```

(Only interesting part is jamal's unusual date format specifiers. For example YYYY would mean YY twice, where YY is the year as in Perl, since 1900.)

Sample run:

```
bash-4.4$ jamal.pl date.jam
2018-03-19

```
> 0 votes

# Answer
# Gema, 40 characters

```
\A=@subst{*\\/*\\/*=\$3-\*-\*;@date}@end

```

Sample run:

```
bash-4.4$ gema '\A=@subst{*\\/*\\/*=\$3-\*-\*;@date}@end'
2018-03-19

```
> 0 votes

# Answer
# Japt, 5 bytes

```
AîKs3

```

Try it

```
A         :10
 î        :Slice the following to that length
  K       :  Current date & time
   s3     :  Convert to ISO string

```
> 0 votes

# Answer
# Forth (gforth), 52 bytes

```
: x 0 <# # # #> ." -"type ; : f time&date 1 .r x x ;

```

Try it online!

### Code Explanation

```
\ x prints a dash followed by a 2-digit number with leading zeros
: x               \ start a new word definition
  0 <# # # #>     \ convert number to double-precision, then converts to a string with leading 0
  ." -"type       \ print "-" followed by the string from the previous command
;                 \ end the word definition

: f               \ start a new word definition
  time&date       \ forth built-in to get the components of a date/time (year on top)
  1 .r            \ print the year (with no space appended)
  x               \ print a dash, followed by the month
  x               \ print a dash, followed by the day
;                 \ end word definition

```
> 0 votes

# Answer
# Nim, 32 bytes

```
import times
echo ($now())[0..9]

```

Try it online!
> 0 votes

# Answer
# TI-Basic (TI-84), 32 bytes

```
Output(1,1,sum(getDate{ᴇ6,ᴇ3,1
Output(1,5,"-
Output(1,8,"-

```
* `getDate` is a list in the form `{2021, 1, 20}`.
* the date list is multiplied by `{1e6, 1e3, 1}` and then summed, giving a single number in the form `yyyy0mm0dd`, this deals automatically with leading zeros
* `-`s are then added at the right places, giving the output `yyyy-mm-dd`
> 0 votes

# Answer
# Thunno 2 `h`, 3 bytes

```
kQO

```

Attempt This Online!

#### Explanation

```
kQ   # Push a string of the current time
     # in the format "YYYY-MM-DD HH:mm:ss"
  O  # Split it on spaces to get the list
     # ["YYYY-MM-DD", "HH:mm:ss"]
     # Implicit output of first item
     # ("YYYY-MM-DD")

```
> 0 votes

---
Tags: code-golf, date
---