title: Is it a leap year?

text:
# Question
Title: Is it a leap year?
This challenge is quite simple. You will take an input which will be a year from 1801 to 2400, and output if it is a leap year or not.

Your input will have no newlines or trailing spaces:

```
1954

```

You will output in any way that you like that clearly tells the user if it is or isn't a leap year (I will accept y or n for yes/no)

You can get a list of leap years here: http://kalender-365.de/leap-years.php I would note that leap years are not ever four years always. 1896 is a leap year, but 1900 is not. The years that follow this "skip" are:

```
1900
2100
2200
2300

```

Test cases:

```
1936 ->  y
1805 ->  n
1900 ->  n
2272 ->  y
2400 ->  y

```

EDIT: This is based on a standard Gregorian calendar: http://www.epochconverter.com/date-and-time/daynumbers-by-year.php

## The Catalogue

The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

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 there 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 snippet:

```
## [><>](https://esolangs.org/wiki/Fish), 121 bytes

```

```
/* Configuration */

var QUESTION_ID = 50798; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 8478; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    else console.log(body);
  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    lang = jQuery('<a>'+lang+'</a>').text();

    languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
```

```
body {
  text-align: left !important;
  display: block !important;
}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 500px;
  float: left;
}

table thead {
  font-weight: bold;
}

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="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f">
<div id="language-list">
  <h2>Shortest Solution 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>
<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>
<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
# APL, ~~16~~ ~~14~~ 12 characters

Returns `0` for a leap year, `1` for a non-leap year.

```
≥/⌽×4 25 4⊤⎕

```

Try this solution on tryapl.org. Note that I have changed the solution to the dfn `{≥/⌽×4 25 4⊤⍵}` as tryapl.com does not support  (take user input). Note that  is an empty box, not a missing character.

The same solution in J:

```
4 25 4>:/@|.@:*@#:]

```

## Explanation

Dyadic  (encode) represents its right argument in the base specified by its left argument. I use base `4 25 4` in this solution. This represents the year *y* as a polynomial

> *y* mod 400 = 100 *a* \+ 4 *b* \+ *c* where *b* \< 100 and *c* \< 4.

Let propositions *α, β,* and *γ* represent if *a,* *b,* and *c* are non-zero: Proposition *γ* is false if *y* is dividable by 4, *β**γ* is false if *y* is dividable by 100 and *α**β**γ* is false if *y* is dividable by 400.

A truth table (`*` representing “don't care”) were proposition Δ represents if *y* is a leap-year obtains:

```
α β γ | Δ
0 0 0 | 1
1 0 0 | 0
* 1 0 | 1
* * 1 | 0

```

The following statement expresses Δ in *α*, *β*, and *γ*:

> Δ = ¬((*α**β*) → *γ*)).

Due to the structure of this statement, one can express ¬Δ as the reduction `≥/⌽α β γ` where ≥ implements ←. This leads to the answer I am explaining right now.
> 23 votes

# Answer
# Javascript (ES6), 21 characters

The standard rule is that `y` is a leap year if 4 divides `y` and if either 100 doesn't divide `y` or 400 does divide `y`. In code,

```
y%4 == 0 && (y%100 != 0 || y%400 == 0)

```

There's no need for that 100 and 400. Instead it suffices to check whether 16 or 4 divides y, with 16 chosen if 25 divides y, 4 otherwise. Golfed, this becomes

```
!(y%(y%25?4:16))

```

A javascript function that implements this is 21 characters long:

```
l=y=>!(y%(y%25?4:16))

```

# Perl, 28 26 characters

Same idea, but in perl.

```
$_=$_%($_%25?4:16)?"n":"y"

```

Run using the `-lp` options. For example,

```
perl -lpe '$_=$_%($_%25?4:16)?"n":"y"'

```

With the test set as input, this produces

```
1936
y
1805
n
1900
n
2272
y
2400
y

```
> 17 votes

# Answer
# Pyth, 11 bytes

```
!%|F_jQ*TT4

```

This full program read from STDIN and prints *True* for leap years and *False* otherwise.

*Thanks to @Jakube for suggesting Pyth and basically porting my CJam code.*

Verify the test cases yourself in the Pyth Compiler/Executor.

### How it works

```
     jQ*TT   Returns the evaluated input in base 10 × 10.
  |F_        Swaps the digit order and reduces using logical OR.
             So far, we've achieved 1954 -> [19, 54] -> 54 || 19.
!%        4  Returns the logical NOT of the result modulo 4.
             This prints True for multiples of 4 and False otherwise.

```
> 16 votes

# Answer
# CJam, 12 bytes

```
rS+2m<~e|4%!

```

This full program read from STDIN and prints 1 for leap years and 0 otherwise.

Verify the test cases yourself in the CJam interpreter.

### How it works

```
r   e# Read from STDIN.
S+  e# Append a space.
2m< e# Rotate two characters to the left.
~   e# Evaluate.
    e# So far, we achieved "1954" -> "54 19" -> 54 19.
e|  e# Logical OR; keep the leftmost non-zero integer.
4%! e# Logical NOT of the kept integer modulo 4.
    e# This pushes 1 for multiples of 4 and 0 otherwise.

```
> 15 votes

# Answer
# TI-BASIC, ~~20 17 16~~ 13

~~Because it is tokenized, TI-BASIC is often competitive at simple math challenges, but not this one since there is no "divisible" command.~~ Maybe it is after all, but this is still longer than CJam and Pyth.

This uses David Hammond's method.

```
not(fPart(Ans/4/4^not(fPart(sub(Ans

```

Old code at 16 bytes:

```
not(fPart(Ans/16not(fPart(sub(Ansnot(fPart(Ans/4

```

Ungolfed:

```
not(fPart(Ans/16) and not(fPart(Ans/100) and not(fPart(Ans/4))))

```

`fPart(` is "fractional part"; exponentiation has higher precedence than division. In TI-BASIC, close-parens are optional.

I use undocumented behavior of the `sub(` command, usually used to get a substring: when its argument is a number instead of a string, it divides the number by 100. It will work on a TI-83 or 84 series calculator.

20 -\> 17 by rearranging code to allow removal of close-parens; 17 -\> 16 by replacing 400 with 16; 16 -\> 13 by using David Hammond's idea.
> 11 votes

# Answer
# Pyth, ~~19~~ ~~15~~ 14 bytes

```
xFm!%Q^d2[2TyT

```

Way too easy. Try it online: Demonstration or Test harness

edit: Missed, that you can print Truthy/Falsy values, instead of `n/y`. -4 byte

edit 2: Used the square root idea of Martin. -1 byte

### Explanation

```
                 implicit: Q = input number
         [         generate a list with the numbers:
          2          2
           T         10
            yT       2*10 = 20
  m              map each number d to:
   !%Q^d2          not(Q mod d^2) // True if Q % d^2 == 0 otherwise False
xF               fold by xor

```
> 10 votes

# Answer
## Regex, ~~83~~ ~~62~~ 38

Thanks to Toby for tips about combining both halves of the regex.

If we focus on 1801..2400 range only and assume input are integers:

```
(?!00)([02468][048]|[13579][26])(00)?$

```

Test in Ruby (`^` = `\A` and `$` = `\Z` because Ruby) for the desired range:

```
r = /(?!00)([02468][048]|[13579][26])(00)?\Z/
(1801..2401).each do |year|
  leap = year % 4 == 0 && ((year % 100 != 0) || (year % 400 == 0))
  leap_regex = !year.to_s[r].nil?
  if leap != leap_regex
    print 'Assertion broken:', year, " ", leap, " ", leap_regex, "\n"
  end
end

```

---

(Bonus) for something that should work not only for 1801..2400, but for any non-negative year:

```
^\d*(0000|(?!00)([13579][26]|(^|[02468])[048])(00)?)$

```

Test in Ruby (`^` = `\A` and `$` = `\Z` because Ruby) for first 100000 years:

```
r = /\A\d*(0000|(?!00)([13579][26]|(\A|[02468])[048])(00)?)\Z/
100000.times do |year|
  leap = year % 4 == 0 && ((year % 100 != 0) || (year % 400 == 0))
  leap_regex = !year.to_s[r].nil?
  if leap != leap_regex
    print 'Assertion broken:', year, " ", leap, " ", leap_regex, "\n"
  end
end

```
> 10 votes

# Answer
# Stackylogic, 226 bytes

Yes, that is right. I made a program in Stackylogic (non-TC), which was invented by Helka Homba, for the challenge found here.

Stackylogic has only binary input, so 10 (or more, any more digits will be ignored) bit binary must be used (least significant bit inputted first). Any dates outside the specified range might fail, as it simply checks what the inputted number is: it doesn't cover unnecessary dates

Not only is this my first challenge with stackylogic, but the first challenge with stackylogic at all.

Get ready for this mess:

```
1
0
1?
010
1?0
010
1?10
?1010
001010
?1010
?1010
?010
?10
?0
0
?
110
?10
11010
?010
11010
?1010
001010
?1010
?1010
?1010
?1010
?010
?0
110
?10
11010
?010
1010
01010
01010
?010
?0
110
?0
110
?0
110
1?0
?10
0?10
?10
?0
01
?
?<
0

```

This took me so long to make, because Stackylogic is the most confusing language I have encountered, and extremely unreadable: you have to know how the rest of the program has executed before you can read the current section being edited. I even had to add spaces for readability while creating it.

## Meagre explanation

This is a simple explanation of what it does.

Stackylogic does not have any mathematical functions, so that made this harder. I had to hardcode most of it, to check if it was a specific number.

First, this program will do a NOR of the least significant bits, discarding them in the process. this means that if it is divisible by 4, it will proceed to the main part of the program, otherwise output 0.

Second, the pointer is carried over to the labyrinth of stackylogic, from here, if the next two bits are zero, it will instantly output 1 (as then it is divisible by 16, and so a leap year despite any other conditions), other wise it will check if it is not any of the numbers that is divisible by 4 but not a leap year, between 1801 and 2400.

To explain in detail, would involve making this post many times longer than it already is
> 10 votes

# Answer
# Haskell, 19 bytes

```
f i=gcd 80i>gcd 50i

```

Try it online!
> 10 votes

# Answer
# JavaScript (*ES6*) 27

The rule: `(y%4==0) && (y%100!=0 || y%400==0)`

Golfed: `!(y%100<1&&y%400||y%4)` (mainly using De Morgans's law)

A function implementing the rule:

```
l=y=>!(y%100<1&&y%400||y%4)

```

A test (run in Firefox) just to be sure:

```
l=y=>!(y%100<1&&y%400||y%4)

for(o=[],i=0;i<700;i++)
  y=i+1800,
  x=l(y),
  o[i/100|0]=(o[i/100|0]||'')+y+(x?' <b>Y</b>':' <i>N</i>')+'\n'

R.innerHTML='<td>'+o.join('</td><td>')+'</td>'
console.log(o[1])
```

```
td { white-space: pre; font-family: monospace; padding: 8px}

b { color: red; }
i { color: blue; }
```

```
<table>
  <tr id=R></tr>
</table>
```
> 9 votes

# Answer
# Pip, 13 bytes

This one was more interesting than it at first appeared. It took some finagling, but I was finally able to replace those lengthy references to `400` with `4` and the `h` variable (=100).

```
!(a%h?aa/h)%4

```

Outputs `1` for leap year, `0` for non-leap year. Explanation:

```
               a is command-line argument (implicit)
  a%h?aa/h     If a is divisible by 100, divide it by 100; otherwise, leave it alone
 (        )%4  The result mod 4 is 0 if it's a leap year, nonzero otherwise
!              Negate and (implicitly) print

```
> 9 votes

# Answer
## IBM System Z assembler - 56 bytes.

## (96 bytes of source. Previously ~~712~~ ~~384~~ 202 bytes of source, 168 byte executable).

Smaller version still. No longer saves caller's registers, changes to literal storage, changed addressing mode.

```
 l        CSECT
         using l,15
         l  5,y
         n 5,f
         bnz r
         xr 4,4
         l 5,y
         d 4,c
         ch 4,i
         bne i
         n 5,f
         bnz r
i        dc h'0'
r        b  *
y        dc f'2004'
f        dc f'3'
c        dc f'100'
         end

```

New version. This will ABEND with a S0C1 if it's a leap year, and loop if it isn't. Hopefully that fulfils the requirement of indicating the result.

```
l        CSECT
         ASMDREG
         SYSSTATE archlvl=2
         IEABRCX  DEFINE
         save  (14,12)
         larl  r9,s
         using s,r9
         st 13,w+4
         la 13,w
         st 13,w+8
         la 5,2004
         st 5,y
         n 5,=f'3'
         bnz r
         xr r4,r4
         l 5,y
         d r4,=f'100'
         ch r4,=h'0'
         bne i
         n 5,=f'3'
         bnz r
i        dc h'0'
r        b  0
s        dc 0d'0'
y        ds f
w        ds 18f
         ltorg
         end

```

OK, so not the shortest (although it might be once we look at the actual executed code plus the interpreter size...)

```
leapyear CSECT
         ASMDREG
         SYSSTATE archlvl=2
         IEABRCX  DEFINE

         save  (14,12)

         larl  r9,staticArea
         using staticArea,r9
         st r13,w_savea+4       .Save callers savearea
         la r13,w_savea         .Address my savearea
         st r13,w_savea+8         . and save it

         open  (O,OUTPUT)             .open file

         la r5,1936             .r5 = input year
         st r5,years            .Save year

         cvd r5,double          .Convert year to p-decimal
         mvc edarea,=xl8'4020202020202120' .Move in edit mask
         ed edarea,double+4      .Make packed decimal year printable
         mvc outrec(4),edarea+4  .Move year string to output area
         bas r10,isitleap       .Call leap year routine

         close (O)              .Close files
         b return               .Branch to finish

isitleap ds 0h
         mvi outrec+5,c'N'      .Set default value
         n r5,=f'3'             .Are last 2 bits 0 (Divisible by 4)?
         bnz notleap            .No - not leap
         xr r4,r4               .Clear R4
         l r5,years             .Reload r5 with year
         d r4,=f'100'           .divide r4/r5 pair by 100
         ch r4,=h'0'            .Remainder 0?
         bne isleap             .No - leap year
         n r5,=f'3'             .Quotient divisible by 4?
         bnz notleap            .No - not leap

isleap   ds    0h
         mvi outrec+5,c'Y'      .Move in leap year indicator

notleap  ds    0h
         put O,outrec           .Print output record
         br r10                 .Return to caller

* Program termination
return   ds 0h
         l r13,w_savea+4         .Restore callers savearea
         return (14,12),,rc=0    .Restore registers and return
* storage areas
staticarea  dc 0d'0'
outrec      ds cl10
years       ds f
w_savea     ds 18f                save area
edarea      ds cl8                    .edit area
double      ds d
* Macros and literals
         print nogen
O        dcb   recfm=F,lrecl=6,dsorg=PS,ddname=O,macrf=PM
         print gen
*
         ltorg                         literal storage
         end

```

Output:

ABEND S0C1 for a leap year, S222 (when the CPU time has run out) if not.

~~1936 Y 1805 N 1900 N 2272 Y 2400 Y~~

~~(when run multiple times)~~
> 8 votes

# Answer
# CJam, ~~18~~ 16 bytes

```
q~[YAK]f{2#%!}:^

```

Gives `1` (truthy) for leap years and `0` (falsy) otherwise.

Run all test cases here.

## Explanation

```
q~                 e# Read and eval input.
  [YAK]            e# Push an array containing 2, 10, 20 (the square roots of the
                   e# relevant divisors).
       f{    }     e# Map this block onto that array, also passing in the input year.
         2#        e# Square the divisor.
           %!      e# Modulo followed by logical negation. Gives 1 if the year is divisible
                   e# by the given divisor and 0 otherwise.
                   e# At this point we have one of the following arrays:
                   e#   [0 0 0] - not a leap year
                   e#   [1 0 0] - a leap year
                   e#   [1 1 0] - not a leap year
                   e#   [1 1 1] - a leap year
              :^   e# Reduce XOR onto this array, which gives 1 if there is an odd number
                   e# of 1s and 0 if there's an even number.

```
> 7 votes

# Answer
# R, 29

```
!(Y=scan())%%4&Y%%100|!Y%%400

```

Test run

```
> !(Y=scan())%%4&Y%%100|!Y%%400
1: 1936
2: 1805
3: 1900
4: 2272
5: 2400
6: 2200
7:
Read 6 items
[1]  TRUE FALSE FALSE  TRUE  TRUE FALSE

```
> 7 votes

# Answer
# Mathematica, ~~40~~ 27 bytes, 17 chars

```
#∣4∧(#∣100<U+F523>#∣400)

```

Uses 17 chars, but 27 bytes. Thanks to @alephalpha for the tip. Note that the vertical bars are actually U+2223 for divides. The `<U+F523>` should be replaced with the corresponding character.
> 6 votes

# Answer
# sed, 55

```
s/00$//
y/0123456789/yNnNyNnNyN/
/N.$/y/ny/yn/
s/.\B//g

```
* First line divides exact centuries by 100.
* Second line gives 'N' to odd digits, 'y' to 4s, and 'n' to non-4s.
* Third line swaps 'y' and 'n' if there's an odd penultimate digit (because 10 is 2 mod 4)
* Final line deletes all but the last character

Note that non-leap years may be printed as `n` or `N` depending on whether they are even or odd. I consider this a creative interpretation of the rule which allows alternatives to 'yes' and 'no' without specifying that they have to be consistent.
> 5 votes

# Answer
# C, 81

I can do shorter, but this one neatly sticks to 'char' types, without parsing the argument (e.g. with `atoi`):

```
main(c,v)char**v;{char*p=*v+9;p-=2*(96==*p+p[1]);putchar("ynnn"[(2**p^p[1])&3]);}

```

It must be invoked with a name 4 characters long, because it makes the standard assumption that arguments immediately follow the program name, separated by NULs. Furthermore, it assumes that the single argument is encoded in ASCII and has no leading space.

### Explanation:

```
main(c,v)
char**v;
{
    char *p = *v+9;
    if (p[0] + p[1] == '0'+'0')
        p -= 2;
    putchar("ynnn"[((*p << 1) ^ p[1])&3]);
}

```

`*v+9` is the position of the 'tens' digit in `v[1]+2`.

If the 'tens' and 'units' characters add to 96, we end in `00`, so back up two characters, so that 'tens' and 'units' point to the century number.

Now xor 'units' with twice the 'tens', mod 4. This works because `10==±2 mod 4`, so the lower bit of the 'tens' can just toggle bit 1 of the 'units'. We use the result as an index into our remainders table, printing `y` only if the modular result is zero.
> 5 votes

# Answer
# Julia, ~~30~~ 28 bytes

```
y->(y%4<1&&y%100>0)||y%400<1

```

This creates an unnamed function that accepts an integer argument and returns a boolean value. To call it, give it a name, e.g. `f=y->...`.

Ungolfed:

```
function f(y)
    (y % 4 == 0 && y % 100 != 0) || y % 400 == 0
end

```

Example:

```
julia> for y in [1936, 1805, 1900, 2272, 2400] println(f(y)) end
true
false
false
true
true
true

```
> 5 votes

# Answer
# Python2 - 37 bytes

```
g=lambda x:(x%4or x%400and x%100<1)<1

```

Note that if `a` is a nonnegative integer, then `a<1` is a short way of writing `not bool(a)`. The last `<1` thus effectively converts the expression in the parentheses to a boolean and negates the result.

Applying the function `g` to an integer `n` between 1801 and 2400 will return `True` if `n` is a leap year, and `False` otherwise.
> 5 votes

# Answer
# Jelly, 7 bytes

```
ọ4,25>/

```

Try it online!

### How it works

```
ọ4,25>/  Main link. Argument: n (1801 - 2400)

ọ4,25    Test how many times n is divisible by 4 and 25.
     >/  Verify that the order of 4 is higher than the order of 25.

```
> 5 votes

# Answer
# Befunge-98, (41 bytes)

```
&:4%#v_:aa*%#v_28*%|
"y",;<;@,"n";>;  ;#[

```

Simplicity is awesome.
> 4 votes

# Answer
# C, ~~37~~ ~~34~~ 30 bytes

```
l(y){y=y%(y%25?4:16)?110:121;}

```

Wandbox
> 4 votes

# Answer
# Python, 37 bytes

```
def c(s):return s%16*(s%25<1)<(s%4<1)

```
> 4 votes

# Answer
# Java 8, ~~49~~ ~~45~~ ~~22~~ 20 bytes

```
n->n%(n%25<1?16:4)<1

```

-2 bytes thanks to *@OlivierGrégoire*.

Try it online.

Some **22 bytes solutions:**

```
n->n%25<1?n%16<1:n%4<1

```

Try it online.

```
n->(n%25<1?n%16:n%4)<1

```

Try it online.

```
java.time.Year::isLeap

```

Try it online.

**Explanation:**

```
n->                // Method with integer parameter and boolean return-type
   n%          <1  //  Return whether the integer is divisible by:
     (n%25<1?      //   If the input is divisible by 25:
             16    //    Check if its divisible by 16
            :      //   Else:
             4)    //    Check if its divisible by 4 instead

```
> 4 votes

# Answer
# C#, 23 bytes

```
y=>y%25<1?y%16<1:y%4<1;

```

**Try it online!**

Full source, including test cases:

```
using System;

namespace CountingLeapYears
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<int,bool>s=y=>y%25<1?y%16<1:y%4<1;
            Console.WriteLine(s(1936)); //y
            Console.WriteLine(s(1805)); //n
            Console.WriteLine(s(1900)); //n
            Console.WriteLine(s(2272)); //y
            Console.WriteLine(s(2400)); //y
        }
    }
}

```
> 4 votes

# Answer
# KDB(Q), 27 bytes

```
{0=x mod(4 400)0=x mod 100}

```

# Explanation

```
               0=x mod 100      / boolean of 100 divisibility
        (4 400)                 / 0b -> 4, 1b -> 400
 0=x mod                        / boolean of 4/400 divisibility
{                         }     / lambda

```

# Test

```
q){0=x mod(4 400)0=x mod 100}1936 1805 1900 2272 2400
10011b

```
> 3 votes

# Answer
## PHP - 45 bytes

```
$b=$argv[1]%400;echo !$b|!($b%4)&!!($b%100);

```

Nothing that special really, just abusing type-juggling.
> 3 votes

# Answer
# T-SQL 37 22 bytes

Saved 15 bytes thanks to BradC's comment.

The usual hardcoded variable for lack of a `stdin`.

e.g.

```
DECLARE @ NVARCHAR(4) = '2016'

```

Then the solution is:

```
PRINT ISDATE(@+'0229')

```
> 3 votes

# Answer
# 05AB1E, ~~9~~ 7 bytes

```
т‰0Kθ4Ö

```

Try it online or verify all test cases.

**Explanation:**

```
т‰         # Divmod the (implicit) input by 100
           #  i.e. 1900 → [19,00]
           #  i.e. 1936 → [19,36]
           #  i.e. 1991 → [19,91]
           #  i.e. 2000 → [20,00]
  0K       # Remove all 0s
           #  i.e. [19,00] → [19]
           #  i.e. [19,36] → [19,36]
           #  i.e. [19,91] → [19,91]
           #  i.e. [20,00] → [20]
    θ      # Pop and get the last item
           #  i.e. [19] → 19
           #  i.e. [19,36] → 36
           #  i.e. [19,91] → 91
           #  i.e. [20] → 20
     4Ö    # Check if it's divisible by 4 (and output the result implicitly)
           #  i.e. 19 → 0 (falsey)
           #  i.e. 36 → 1 (truthy)
           #  i.e. 91 → 0 (falsey)
           #  i.e. 20 → 1 (truthy)

```
> 3 votes

# Answer
## Javascript ES6, 32, 29, 26

Any of following lines works:

```
f=y=>new Date(y,2,0).getDate()&1
g=y=>!(y&3)^!(y%100)>!(y%400)
h=y=>!(y&3|y%100<1&&y%400)

```
> 2 votes

# Answer
# C, 57 bytes

Takes the input from stdin, with or without trailing spaces/newline. Only works on little endian machines (yeah, like everyone is on BE these days). Outputs Y or N.

```
main(y){scanf("%d",&y);y=y%(y%100?4:400)?78:89;puts(&y);}

```

## Explanation

Ungolfed:

```
int main(int y) {
   scanf("%d", &y);
   y = y % (y % 100 ? 4 : 400) ? 'N' : 'Y';
   puts(&y);
}

```

First, `scanf` reads the year as an integer in y. Then, y is modulo'ed with 4 or 400 depending on whether the year is divisible by 100. If the remainder is zero, the ASCII code for Y is assigned to y, otherwise it gets the ASCII code for N. The value of y is now `0x000000??`, where `0x??` is the assigned character. Being on a little-endian machine, in memory this is stored as `?? 00 00 00`. This is a NULL-terminated C string, containing only the assigned characters. The address of y is passed to puts and the char is printed (with a trailing newline).
> 2 votes

# Answer
# Haskell, ~~43~~ ~~41~~ 39 bytes

```
l x=mod x(if mod x 25<1then 16else 4)<1

```

If x is divisible by 25, check if it is also divisible by 16, making it divisible by the least common multiple of 25 and 16, which is 400.
If x is not divisible by 25, check if it is divisible by 4.

*Inspired by @David Hammen's answer in JavaScript.*
> 2 votes

# Answer
# PHP, ~~34~~ 30 bytes

```
echo+!($argn%($argn%25?4:16));

```

I'm using the `+` sign to convert `false` (which would normally be converted to an empty string) to `0`, because that seems to comply closer to the "clearness" requirement (maybe not?). With standard truthy/falsy rules, 1 byte can be saved.

Note: I shamelessly implemented the divisibility by 25 trick from @David Hammen. Without his algorithm it would be 37 bytes:

```
<?=+!(($b=$argv[1])%400^$b%100^$b%4);

```

Run like this:

```
echo 1900 | php -nR 'echo+!($argn%($argn%25?4:16));';echo

```

# Tweaks

* Saved 4 bytes by using `$argn`
> 2 votes

# Answer
# PowerShell, 31 bytes

I am excited to say that I golfed this shorter than the builtin!

```
param($a)!($a%(4,16)[!($a%25)])

```

Outputs true for leap years and false otherwise.

Builtin:

```
[datetime]::IsLeapYear($args[0])

```

Though, if I wanted to stretch the statement 'clearly tells the user if it is or isn't a leap year' and do something non-standard, I could save 3 bytes and use:

```
param($a)$a%(4,16)[!($a%25)]

```

This outputs `0` for leap years and 1 or higher for non-leap years, which I don't like since I'd prefer to return a more standard truthy value for leap years.
> 2 votes

# Answer
## LOLCODE, ~~228~~ ~~202~~ 159 bytes

```
HOW IZ I f YR a
MOD OF a AN 100
O RLY?
YA RLY
MOD OF a AN 4
O RLY?
YA RLY
b R 1
OIC
NO WAI
MOD OF a AN 400
O RLY?
YA RLY
b R 0
NO WAI
b R 1
OIC
OIC
IF U SAY SO

```

Ungolfed:

```
HAI 1.3 BTW "HAI" does nothing functionally in current versions and does not throw an error if you omit it.
HOW IZ I leap YR input
    I HAS A output
    DIFFRINT MOD OF input AN 100 AN 0 BTW Thanks @LeakyNun, In LOLCODE any non-empty values, i.e. 0, "", etc. default to WIN.
    O RLY?
        YA RLY
            BOTH SAEM MOD OF a AN 4 AN 0
            O RLY?
                YA RLY
                    output R WIN BTW "WIN" is true, but in the actual program I used 1 as a truthy value because it's shorter.
            OIC
        NO WAI
            DIFFRINT MOD OF a AN 400 AN 0
            O RLY?
                YA RLY
                    output R FAIL BTW "Fail" is false, but in the actual program I used 0 as a falsy value.
                NO WAI
                    output R WIN
            OIC
    OIC
    FOUND YR output BTW This statement is implied in the golfed version.
IF U SAY SO BTW "KTHXBYE", just like "HAI" has no functional purpose and throws no error on omission.
KTHXBYE

```

In Python ungolfed, because LOLCODE is confusing:

```
def leap:
    if(year % 100 != 0):
        if(year % 4 == 0):
            output = true
    else:
        if(year % 400 != 0):
            output = false
        else:
            output = true
    return(output)

```
> 2 votes

# Answer
# Mathematica, 15 bytes

```
LeapYearQ@*List

```

Mathematica has a built-in for everything. `List` is there to make the integer input into a compact `DateList` object. Returns `True` or `False`.
> 2 votes

# Answer
# PHP, 28 bytes

Why calculate when there´s a builtin?

```
<?=checkdate(2,29,$argv[1]);

```

prints `1` for leap year, empty string for no leap year.
Add `+` after `<?=` for `1`/`0`.
> 2 votes

# Answer
# SmileBASIC, 40 bytes

```
INPUT Y?0DTREAD STR$(Y)+"/02/29"OUT,,,?1

```

Prints `0` `1` if it's a leap year, otherwise prints `0` and errors.

`DTREAD` parses a date string in the form of `YYYY/MM/DD` and gives the year, month, and day. It can also return the day of the week, and trying to get the day of the week of a day that doesn't exist (Feb. 29 of a non-leap year) will cause an error.

This is shorter than the obvious answer using mod, because SB uses `MOD` instead of `%`, which takes up 3-5 characters.
> 2 votes

# Answer
# x86 machine code, 16 bytes

```
00000000: fcad fdad 2d30 3074 fa86 c4d5 0aa8 03c3    ...-00t.........

```

**Listing**

```
FC         CLD             ; set direction for LODSW to increment
AD         LODSW           ; SI += 2 to start with last two digits
FD         STD             ; set direction for LODSW to decrement
       LD:
AD         LODSW           ; load two ASCII digit chars into AX
2D 3030    SUB  AX, '00'   ; convert to decimal, test if year ends in 00?
74 FA      JZ   LD         ; if so, look at the first two digits instead
86 C4      XCHG AL, AH     ; endian convert
D5 0A      AAD             ; base convert from 10 to word
A8 03      TEST AL, 3      ; mod 4 = 0?
C3         RET             ; return to caller

```

Input string in `SI`, output is `ZF` if is a leap year.

**Explanation**

If the year does not end in `00`, it is a leap year if last two digits `mod 4` is `0`. If it does end in `00`, it will be a leap year if the first two digits `mod 4` is `0`. Example:

Leap year:

* 19**36**: `36 mod 4 == 0`
* **24**00: `24 mod 4 == 0`

NOT leap year:

* 18**05**: `05 mod 4 == 1`
* **19**00: `19 mod 4 == 3`

**Test Program Output**
> 2 votes

# Answer
# Excel, ~~30~~ 25 bytes

Because of an intentional bug in Excel to maintain compatibility with Lotus 1-2-3 the year 1900 is treated as a leap year. We can however shift the year by 400 before doing the calculation. The leap year bug then occurs in 1500, which we don't care about anyway. For the following formula A1 serves as input.

```
=DAY(DATE(A1+400,2,29))>1

```
> 2 votes

# Answer
# Python 3, 26 bytes

```
lambda n:n%4**-~(n%25<1)<1

```

Try it online!

Using Kevin Cruijssen's Java approach.

---

# Python 3, 28 bytes

```
lambda n:(n%100or n/100)%4<1

```

Try it online!

Using Kevin Cruijssen's 05AB1E approach.
> 2 votes

# Answer
# Ruby, 28 bytes

The lambda takes an Integer `y` representing the year and returns true or false.

```
->y{y%4<1&&y%100>0||y%400<1}

```

Use like this:

```
f=->y{y%4<1&&y%100>0||y%400<1}
f[2004]
# => true

```

or this:

```
f=->y{y%4<1&&y%100>0||y%400<1}
[1936,1805,1900,2272,2400].map(&f)
# => [true, false, false, true, true]

```

Try it online

## Explanation

* `y%4<1&&y%100>0`
    + Years that are divisible by 4 but not by 100 are leap years, e.g. 2004
    + Years that are divisible by 4 and also by 100 are not leap years, e.g. 1700
* `y%400<1`
    + Years that are divisible by 400 are leap years, e.g. 1600
> 2 votes

# Answer
# Arturo, 5 bytes

```
leap?

```

Try it!
> 2 votes

# Answer
# SpecBAS - 77

Not the shortest (but not the longest either).

```
1 INPUT y: PRINT y;"->";"ny"((y MOD 4=0 AND (y MOD 100<>0) OR y MOD 400=0)+1)

```

Uses the standard formula, then prints "n" or "y" based on return value (the final +1 at the end is due to strings being 1-based).
> 1 votes

# Answer
# Python, ~~50~~ 48 bytes

```
import calendar as y
def a(b):print(y.isleap(b))

```
> 1 votes

# Answer
# C#, 26 bytes

```
y=>DateTime.IsLeapYear(y);

```

C# lambda (`Predicate`) where the input is a `int` and the output is a `bool`. I use a builtin.
> 1 votes

# Answer
## BASH, 68 bytes

```
((!(y % 4) && ( y % 100 || !(y % 400)))) &&  echo "leap" || echo "no"

```
> 1 votes

# Answer
## Retina, 24 bytes

```
[^04]00$

.+
$*
....

^$

```

Try it online!
> 1 votes

# Answer
# PHP, 45 bytes

```
<?=date_create($argv[1].'-1-1')->format('L');

```

Not the shortest, but using built in functions. Totally not code-golf.
> 1 votes

# Answer
# Jelly, 8 bytes

```
ȷ2*ḍ¥×4ḍ

```

Try it online!
> 1 votes

# Answer
# Bash, 14 bytes

```
date -d$1/2/29

```

Try it online!

Outputs via exit code, `0` for leap year and `1` otherwise.

`date -d STRING` will display the date indicated by `STRING`. `$1/2/29` represents February 29th of `$1`, the argument. If `STRING` is not valid, i.e. Feb 29 does not exist, then `date` errors out.
> 1 votes

# Answer
## C++, ~~50~~ 43 bytes

-7 bytes thanks to Zacharý

```
int l(int y){return!(y%4)&&y%100+!(y%400);}

```

And the test code is :

```
auto t = {
    1936,1805,1900,2272,2400
};

for (auto&a : t) {
    std::cout << "Year : " << a << " is " << (l(a) ? "" : "NOT") << " a leap year\n";
}

```
> 1 votes

# Answer
# Ruby, 22 bytes

```
->n{1>n%(n%25<1?16:4)}

```

Try it online!

The challenge is quite old, but I noticed there was no valid Ruby answer yet. Nothing particularly original, anyway.
> 1 votes

# Answer
# , ~~43~~ 42 bytes

```
T l(T)(T y){return!(y%4)&&y%100+!(y%400);}

```

Try it online!

Another port of @HatsuPointerKun's C++ answer.
> 1 votes

# Answer
# Kotlin, 30 bytes

```
{it%4<1&&(it%100>0||it%400>0)}

```

Try it online!
> 1 votes

# Answer
# Common Lisp, 46 bytes

```
(=(mod(setq x(read))(if(>(mod x 25)0)4 16))0)

```

Try it online!

Based on the David Hammen’s method.
> 1 votes

# Answer
# Clam, ~~33~~ 31 bytes

```
=a*rp|e%a*"400"0&%a*"100"e%a*40

```

Try it online!

*-2 bytes thanks to ASCII-only*

Outputs `true` for leap years. Outputs `false` for other years

## Explanation

```
=a*rp|e%a*"400"0&%a*"100"e%a*40
=a*r                             read input and store in a*
    p                            Print..
       %a*"400"                    a* % 400
      e                            ==
               0                   0
     |                             OR
                 %a*"100"            a* % 100
                &                    AND
                          %a*4       a* % 4
                         e           ==
                              0      0

```

Very awkward explanation, but basically what it does is this:

```
print(year % 400 == 0 || (year % 100 && year % 4 == 0))

```

Clam follows JS rules for truthy and falsey values, meaning `year % 100` is true if it does *not* equal 0 (and it's shorter than adding an `e` before it and an `0` after it)

Resulting JS:

```
myVar = read();
console.log(year % 400 == 0 || (year % 100 && year % 4 == 0));

```
> 1 votes

# Answer
# MathGolf, 9 bytes

```
4♀`*]÷~≤*

```

Try it online!

## Explanation

```
4         Push 4
 ♀        Push 100
  `*      Duplicate top two elements of stack and multiply (400)
    ]     Wrap stack in array ([4, 100, 400])
     ÷    Check input for divisibility with all array items
      ~   Dump array onto stack
       ≤  Check if divisibility by 100 is <= than divisibility with 400
        * Multiply with the divisibility bool for 4, works like logical and

```

The trick is that  ensures that if a number is divisible by 100, it must also be divisible by 400, but if it's not divisible by 100, anything goes.
> 1 votes

# Answer
# Japt `-!`, ~~8~~ 5 bytes

Locale dependent; in my locale the timezone offset is `GMT+0000` for leap years and `GMT-0025` for all others.

```
ÐUT k

```

Try it or run all test cases

```
ÐUT k     :Implicit input of integer U
Ð         :Create Date object from (defaulting to the first day of the month)
 U        :  The year U
  T       :  The month 0 (months are 0-indexed in JS)
    k     :Get timezone offset as an absolute integer (0 or 25)
          :Implicit output of logical NOT of result

```

And here's my original 8-byte solution, which isn't locale dependent and outputs `1` or `0` for `true` & `false`:

```
ÐUT#< Îu

```

Try it (includes all test cases)

```
ÐUT#< Îu     :Implicit input of integer U
ÐUT          :As above but ...
   #<        :  With the date set to 60 (dates wrap over to the next month in JS, so this will give us either 29/02 or 01/03)
      Î      :Get 0-based index of month (1 or 2)
       u     :Modulo 2

```
> 1 votes

# Answer
# Japt `-h!`, 8 bytes

Input is taken as a string.

```
k0 ò o%4

```

Try it online!
> 1 votes

# Answer
# Haskell, 35 bytes

```
l x|x!25<1=x!16<1
l x=x!4<1
(!)=mod

```

Try it online!
> 1 votes

# Answer
# PHP, ~~35~~ 34 bytes

*-1 byte thanks to 640KB*

```
<?=date(L,strtotime($argv[1].-1));

```

Try it online!

Came across the `L` option in the PHP date formatter, which returns if the year of the date is a leap year. After that, it was just a matter of trying to get the timestamp of the year in the shortest way (though I'm not too confident this *is* the shortest)
> 1 votes

# Answer
## Reg, 14 bytes

```
1¿:%[4|]%[;]

```

Try it online!

How it works (because it contains unprintable characters)
> 1 votes

# Answer
## `d`, ~~10~~ 8 bytes

```
Ö♦Ç⌂╬`§Γ

```

## Explanation:

Uncompressed:

```
25m4&16|m!

```

```
25m        % If the input is modulo-able by 25:
   4&      % Return 4
     16|   % Otherwise, return 16
        m! % Modulo input by the value. Negate the value.

```
> 1 votes

# Answer
# Forth (gforth), ~~<sup>48</sup>~~ 39 bytes

```
: f 'd /mod over if d>s then 4 mod 0= ;

```

Try it online!

Same as Kevin Cruijssen's 05AB1E answer.

-9 bytes from Bubbler.
> 1 votes

# Answer
# Vyxal, ~~13~~ 10 bytes

<sup>-3 bytes Thanks to Kevin Cruijssen</sup>

```
25Ḋ[16|4]Ḋ

```

Outputs 1 for truthy, 0 for falsy

Try it Online!

## Explanation

```
25Ḋ           - is it divisible by 25?
   [16   Ḋ    - if so: check if its divisible by 16
      |4]Ḋ    - if not: check if its divisible by 4

```

---

# Vyxal, 7 bytes

A port of Kevin Cruijssen's answer

```
₁ḋ0ot4Ḋ

```

Try it Online!

## Explanation

```
₁ḋ       - divmod the input by 100
  0o     - remove all instances of 0 from the result
    t4Ḋ  - grab the tail of the divmod result and check if it's divisible by 4

```
> 1 votes

# Answer
## Python, 125 bytes

```
y=int(input(""))
if y%100==0 and y!=2400:
    print("n")
else:
    if y%4==0:
        print("y")
    else:
        print("n")

```

Try it Online!
> 1 votes

# Answer
## Pascal, 100 B

This is a complete `program` according to and requiring a processor complying to ISO standard 7185 “Pascal” (level 0 sufficient). It demonstrates the importance of sets in Pascal. Note, `+` and  are left-associative thus the following is guaranteed to yield the expected result.

```
program p(input,output);var y:integer;begin read(y);write(0 in[y mod 4]-[y mod 100]+[y mod 400])end.

```

For the standard non-golfed version using `Boolean` operators `and`/`or` see RosettaCode.

## Delphi/Free Pascal, 62 B

The `.toInt64` “type helper” requires at least FPC version 3.0.0. In FPC, `{$mode Delphi}` or `{$mode objFPC}` have to be selected so `paramStr` returns “long strings”. Evidently, input is specified as the first argument on the command line.

```
{$mode Delphi}
uses sysUtils;begin write(isLeapYear(paramStr(1).toInt64))end.

```

This is pretty much the same as the RosettaCode implementation.
> 1 votes

# Answer
# Fig, \\$11\log\_{256}(96)\approx\\$ 9.054 bytes

```
?%25x%4x%16

```

Try it online!

Port of Vyxal. Outputs 0 for truthy, positive numbers for falsey.

```
?%25x%4x%16
?%25x       # If mod 25 is > 0
     %4x    # Print mod 4
        %16 # Else print mod 16

```
> 1 votes

# Answer
# Go, 47 bytes

```
func(y int)bool{return y%4<1&&y%100>0||y%400<1}

```

Attempt This Online!
> 1 votes

# Answer
# Thunno 2 `t`, 6 bytes

```
ɦḋ0o4Ḋ

```

Attempt This Online!

Port of Kevin Cruijssen's 05AB1E answer.

#### Explanation

```
ɦḋ0o4Ḋ  # Implicit input
ɦḋ      # Divmod by 100
  0o    # Remove 0s
    4Ḋ  # Divisible by 4?
        # Implicit output
        # of last item

```
> 1 votes

# Answer
# MATLAB + Aerospace Toolbox, 9 bytes

```
@leapyear

```

Anonymous function that determines if the passed year is a leap year, returning 1 for leap and 0 for not.

Ok so MATLAB has a built-in... But there we are.

---

# Octave, 13 bytes

```
@is_leap_year

```

Try it online!

Octave also has a built-in... cost's 4 more bytes than MATLAB though.
> 0 votes

# Answer
# Whitespace, 103 bytes

```
[S S S N
_Push_0][S N
S _Duplicate_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve][S N
S _Duplicate_input][S S S T T   S S T   N
_Push_25][T S T T   _Modulo][N
T   S T N
_If_0_jump_to_Label_TRUE][S S S T   S S N
_Push_4][T  S T T   _Modulo][N
T   S S N
_If_0_jump_to_Label_LEAP][N
S N
N
_Jump_to_Label_PRINT][N
S S T   N
_Create_Label_TRUE][S S S T S S S S N
_Push_16][T S T T   _Modulo][N
T   S S N
_If_0_jump_to_Label_LEAP][N
S N
N
_Jump_to_Label_PRINT][N
S S S N
_Create_Label_LEAP][S S S T N
_Push_1][N
S S N
_Create_Label_PRINT][T  N
S T _Print_as_integer]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

### Explanation in pseudo-code:

```
Integer i = STDIN-input as integer
If i modulo-25 is 0:
  If i modulo-16 is 0:
    Print 1
  Else:
    Print 0
Else-if i modulo-4 is 0:
  Print 1
Else:
  Print 0

```

### Example runs:

**Input: `1936`**

```
Command     Explanation                Stack            Heap       STDIN    STDOUT   STDERR

SSSN        Push 0                     [0]              {}
SNS         Duplicate top (0)          [0,0]            {}
SNS         Duplicate top (0)          [0,0,0]          {}
TNTT        Read STDIN as integer      [0,0]            {0:1936}   1936
TTT         Retrieve at heap 0         [0,1936]         {0:1936}
SNS         Duplicate top (1936)       [1936,1936]      {0:1936}
SSSTTSSTN   Push 25                    [1936,1936,25]   {0:1936}
TSTT        Modulo                     [1936,11]        {0:1936}
NTSTN       If 0: Jump to Label_TRUE   [1936]           {0:1936}
SSSTSSN     Push 4                     [1936,4]         {0:1936}
TSTT        Modulo                     [0]              {0:1936}
NTSSN       if 0: Jump to Label_LEAP   []               {0:1936}
NSSSN       Create Label_LEAP          []               {0:1936}
SSSTN       Push 1                     [1]              {0:1936}
NSSN        Create Label_PRINT         [1]              {0:1936}
TNST        Print top as integer       []               {0:1936}            1
                                                                                error

```

Program stops with an error: No exit defined.
Try it online (with raw spaces, tabs and new-lines only).

**Input: `2400`**

```
Command     Explanation                Stack            Heap       STDIN    STDOUT   STDERR

SSSN        Push 0                     [0]              {}
SNS         Duplicate top (0)          [0,0]            {}
SNS         Duplicate top (0)          [0,0,0]          {}
TNTT        Read STDIN as integer      [0,0]            {0:2400}   2400
TTT         Retrieve at heap 0         [0,2400]         {0:2400}
SNS         Duplicate top (2400)       [2400,2400]      {0:2400}
SSSTTSSTN   Push 25                    [2400,2400,25]   {0:2400}
TSTT        Modulo                     [2400,0]         {0:2400}
NTSTN       If 0: Jump to Label_TRUE   [2400]           {0:2400}
NSSTN       Create Label_TRUE          [2400]           {0:2400}
SSSTSSSSN   Push 16                    [2400,16]        {0:2400}
TSTT        Modulo                     [0]              {0:2400}
NTSSN       If 0: Jump to Label_LEAP   []               {0:2400}
NSSSN       Create Label_LEAP          []               {0:2400}
SSSTN       Push 1                     [1]              {0:2400}
NSSN        Create Label_PRINT         [1]              {0:2400}
TNST        Print top as integer       []               {0:2400}            1
                                                                                error

```

Program stops with an error: No exit defined.
Try it online (with raw spaces, tabs and new-lines only).

**Input: `1991`**

```
Command     Explanation                Stack            Heap       STDIN    STDOUT   STDERR

SSSN        Push 0                     [0]              {}
SNS         Duplicate top (0)          [0,0]            {}
SNS         Duplicate top (0)          [0,0,0]          {}
TNTT        Read STDIN as integer      [0,0]            {0:1991}   1991
TTT         Retrieve at heap 0         [0,1991]         {0:1991}
SNS         Duplicate top (1991)       [0,1991,1991]    {0:1991}
SSSTTSSTN   Push 25                    [0,1991,1991,25] {0:1991}
TSTT        Modulo                     [0,1991,16]      {0:1991}
NTSTN       If 0: Jump to Label_TRUE   [0,1991]         {0:1991}
SSSTSSN     Push 4                     [0,1991,4]       {0:1991}
TSTT        Modulo                     [0,3]            {0:1991}
NTSSN       if 0: Jump to Label_LEAP   [0]              {0:1991}
NSSN        Create Label_PRINT         [0]              {0:1991}
TNST        Print top as integer       []               {0:1991}            0
                                                                                error

```

Program stops with an error: No exit defined.
Try it online (with raw spaces, tabs and new-lines only).
> 0 votes

# Answer
# ActionScript 2.0, 49 bytes

```
function a(b){trace(!(b%4)&&b%100+!(b%400)?1:0);}
function a(b){                                  } - define a function
              trace(                          );  - that outputs
                                          ?       - if
                    !(b%4)                        - the input divides by 4
                          &&                      - and
                            b%100                 - doesn't divide by 100
                                 +                - plus
                                  !(b%400)        - does divide by 400
                                           1:0    - 1, else 0

```

Not a very good explanation, and I might have swapped some stuff, but this still confuses me, so this is the best you're going to get.
> 0 votes

# Answer
# C (gcc), 33 bytes

```
f(i,a){a=!(i%4|!(i%100)&&i%400);}

```

Try it online!
> 0 votes

# Answer
# JavaScript, 19 bytes

```
y=>!(y%25?y%4:y%16)

```

Try it online!
> 0 votes

# Answer
**Swift, 82 bytes**

```
func l(y:Int){y%4==0 && (y%100 != 0 || y%400==0) ?print("Y"):print("N")}
l(y:1936)

```

Try it online!
> 0 votes

# Answer
A leap year `ERE` is not a "language" per se but it should be easily adaptable to any flavor of regex

(I *think* it should work for ***any*** year, including negative years and also waaaaaaay in the future, assuming `proleptic Gregorian calendar`)

```
ereLEAP := /(([2468][048]|[13579][26]|(^|[0+-])[48])(00)?|0000|^[+-]?0*)$/

```

so an `awk` solution using it would be like

---

```
awk 'function leap(_) {
         return _~"(([2468][048]|[13579][26]|(^|[0+-])" \
                  "[48])(00)?|0000|^[+-]?0*)$" ? "y" : "n" } ($2 = leap($1))^_'

```

---

and it properly captures the special edge cases, including strangely formatted inputs like negative zero :

```
-2400
-2000
-1600
-1200
-800
-400
-0
0
400
800
1200
1600
2000
2400

777778000
777778400
777778800
777779200
777779600
777780000
777780400
777780800
777781200
777781600
777782000
777782400

```

or ultra extreme inputs, like the year

```
9745314011399999080353382387875188310876226857595007526867
9064572129486907664261024656150658820102592253049162314086
6818345916986520309404657798729631265341953127769995647302
9870789655490053648352799593479218378873685597925394874945
746363615468965612827738803104277547081828589991914111200

```
> 0 votes

---
Tags: code-golf, date, decision-problem
---


# Question
Title: Sokobunny I (Sokoban, but the boxes are sentient)
# Sokobunny 1

**You *love* buns!** You love them so much, that you chased one down a bunburrow. The burrows are like mazes, and **YOU WANT TO CATCH THE FLUFFBALLS!!!!** However, the buns are smart! You can't catch the bun by by chasing after it, as you *wait out of politeness for the buns*.

Taken from the game `Paquerette Down the Bunburrows` (This is imo easily the best puzzle game out there, as it is ***meta*** **meta** *meta* *meta* ... *echoes until inaudible*)

## Bun behavior

* Buns will run straight away from you if they can, until they reach a tile with a non-wall left or right. It they see no exits, they run straight ahead.
* A bun is comfortable until you are closer than two squares (manhattan), this means a bun will keep a distance of two empty squares horizontally and vertically, but won't care about diagonals.
* A bun won't choose to go into a dead end it can see.
* A bun can see horizontally and vertically and and tell if it is a straight dead end.
* A bun can see all adjacent squares (horiz, vert, and diag)
* A bun will prefer to turn left, if given the choice.
* A bun is captured if on the same tile as a player.

## Challenge:

Shortest wins!

* Global guarantees: No buns will ever be harmed in the making of these challenges.
* Guarantees (this challenge only):
    + no bun will be captured
    + no bun will run out of bounds
    + mazes will always be a rectangle
* Inputs:
    + Ascii Maze: `#` is a wall, and  is not
    + Player position. (Col, row), starting from top-left at (0, 0)
    + Bunny position. Same scheme
* Outputs:
    + New bunny position
    + All rotated inputs should output the same relative position
* You must treat any non `#` character as a wall. This applies expressly to the `P` and `B` characters.

the bun after it moves (if it does).

Visual representation (Not valid for challenge):
B is bun, b is where bun goes.
███████████████████████████████████████
████████████████████████   ███   ██████
█████████████████████               ███
██████████████████████████████   ██████
██████          P     B------->b    ███
████████████   ████████████████████████
███████████████████████████████████████

Maze:
#############
######## # ##
#######     #
########## ##
##   P B    #
#### ########
#############
Player: (5, 4)
Bun:    (7, 4)

Output: (10, 4)

Maze:
#############
######## # ##
#######     #
########## ##
##      P B #
#### ########
#############
Player: (8, 4)
Bun:    (10, 4)

Output: (10, 2)

Maze:
############################
#P B                       #
######################### ##
############################
Player: (1, 1)
Bun:    (3, 1)

Output: (25,1)

Maze:
######
### ##
#P B##
###  #
######
Player: (1, 2)
Bun:    (3, 2)

Output: (3, 3)

Maze:
#######
###  ##
## B###
##  ###
###P###
#######
Player: (3, 4)
Bun:    (3, 2)

Output: (2, 2)

Maze:
#######
#P  B #
#######

Player: (1, 1)
Bun:    (4, 1)

Output: (4, 1)

Maze:
#######
# P B #
#######

Player: (2, 1)
Bun:    (4, 1)

Output: (5, 1)

Maze:
#######
#  PB #
#######

Player: (3, 1)
Bun:    (4, 1)

Output: (5, 1)
```
</code></pre>

# Answer
> 3 votes
# Python3, 791 bytes:

```
M=[(0,1),(0,-1),(1,0),(-1,0)]
def F(b,x,y,X,Y,s):
 q,s=[(X,Y)],s+[(X,Y)]
 while q:
  X,Y=q.pop(0)
  for J,K in M:
   if(U:=(X+J,Y+K))not in s and' '==b[X+J][Y+K]:yield(*U,(J,K));q+=[U];s+=[U]
def f(b,c,C):
 (y,x),(Y,X)=c,C
 q=[(X,Y,*([(0,-1),(0,1)][y<Y]if x==X else[(-1,0),(1,0)][x<X]),[])]
 while q:
  X,Y,j,k,s=q.pop(0);P=abs(x-X)+abs(y-Y)>2
  T=[((J,K),any(B!=(J,K)for B in F(b,x,y,X+J,Y+K,[(X,Y)])))for J,K in M if(X+J,Y+K)not in s and' '==b[X+J][Y+K] and abs(x-X)+abs(y-Y)<abs(x-X-J)+abs(y-Y-K)]
  T=[(a,b)for a,b in T if b or not any(B for _,B in T)]
  if[]==T or (len(T)==1 and not T[0][1]and P):return(X,Y)
  if any(i[0]!=(j,k)for i in T)and P:return(X,Y)
  if(K:=[(0,j),(-1*k,0)][k!=0])in[i[0]for i in T]and P:return(X+K[0],Y+K[1])
  for(J,K),_ in T:q+=[(X+J,Y+K,J,K,s+[(X+J,Y+K)])]

```

Try it online!

---
Tags: code-golf, ascii-art, maze
---


title: Calculate the day number of the year

text:
# Question
Title: Calculate the day number of the year
Seems like we do not have this one yet, so here we go:

# The Challenge

Write a program or function that takes a date as input and outputs the day number of the year. You may not use any builtins for that!

# Rules

* As usual you may write a full program or a function.
* The format of the input is up to you, but it has to contain a year, a month and a day. Make clear which one your solution uses!
* No date-related builtins allowed! You gotta do the work by yourself. Builtins which are not related to date operations are fine.
* Base for the calcultion is the gregorian calendar.
* You have to take account of leap-years.
* You only need to handle years in the range \[1, 9999\]
* Standard loopholes are forbidden.
* Lowest byte count wins!

# Testcases

Input format here is YYYY/MM/DD

```
2016/07/05 -> 187
2000/03/28 -> 88
0666/06/06 -> 157
6789/10/11 -> 284
0004/04/04 -> 95
1337/07/13 -> 194

```

Happy Coding!

# Answer
## Pyth, 31 bytes

```
+s<X1+L28jC"3»î"4!%|F_jQ*TT4tEE

```

Thanks to @Dennis and @Jakube for the leap year portion. Input is YYYY, MM, DD on separate lines.

```
+                          add [day] to
  s <                      sum of first [month]-1 values in the list
      X                    add 1 to
        1                  the second element (January)...
        +L                 \
           28              |
           j               }   lengths of all the months
             C "3»î"       |
             4             /
        ! %                ... if the year is a leap year; that is, 4 divides...
            |F _ j         fold logical OR over reversed
                   Q       the year
                   *TT     converted to base 100
            4
      t E                 [month]-1
  E                       [day]

```

Test suite.
> 2 votes

# Answer
## JavaScript ES6, ~~81~~ 69 bytes

```
(y,m,d)=>d+parseInt("03479cehkmpr"[--m],36)+m*28-(y%(y%25?4:16)&&m>1)

```

Assuming months are 1-based, otherwise I could save 2 bytes.

Edit: Saved 12 bytes using @user81655's tip.
> 7 votes

# Answer
# C, ~~96~~ ~~102~~ ~~89~~ 61 bytes

```
g(y,m,d){printf("%d",m/2*31+--m/2*30-(y%(y%25?4:16)?2:1)+d);}

```
> 3 votes

# Answer
# Python 3, ~~152~~ ~~148~~ 150 bytes

```
m,d,y=map(int,input().split());n=[0,31,(59,60)[(y%4==0 and y%100!=0)or y%400==0]]
for i in range(m):n+=[n[-1]+(31,30)[i in[1,3,6,8]]]
print(n[-4]+d)

```

Takes dates in the format "M D YYYY".
> 2 votes

# Answer
# Python 2, 100 82 bytes

A Python port of @Neil's answer:

```
lambda d,m,y:d+int("03479cehkmpr"[m-1],36)+(m-1)*28-(y%(4if y%25 else 16)and m>2)

```

As with the previous answer, adding 17 bytes (99 bytes total) will yield a full program:

```
print(lambda d,m,y:d+int("03479cehkmpr"[m-1],36)+(m-1)*28-(y%(4if y%25 else 16)and m>2))(*input())

```

## Previous answer:

As an anonymous lambda:

```
lambda d,m,y:d+sum(31-(n in(3,5,8,10))for n in range(m-1))-(3if y%4 or(y%400!=0and y%100==0)else 2)

```

Can be converted to a named lambda for a 2 byte penalty. Alternatively, a full program (taking input in the format `D,M,Y`) can be achieved for 117 bytes:

```
print(lambda d,m,y:d+sum(31-(n in(3,5,8,10))for n in range(m-1))-(3if y%4 or(y%400!=0and y%100==0)else 2))(*input())

```
> 2 votes

# Answer
# Nibbles, 28 bytes

```
+-=@`\:0.``@1370+30$+?-@2- 2%+.::4 100 400^0%_$~0

```

Attempt This Online!

Takes the year, month and day as command-line arguments.

Edit: Care to explain why this was downvoted?
> 1 votes

# Answer
# Python 3, 125 bytes

```
print((lambda d,m,y:sum([3,not(y%400 and not y%100 or y%4),3,2,3,2,3,3,2,3,2,3][:m-1])+m*28-28+d)(*map(int,input().split())))

```

An another approach to this problem. The code takes advantages of the Python's boolean algebra execution priorities and since `not` is the last operation, conversion to boolean is automatic. When summation is done, the boolean is treated as 1 or 0. Input format is "YY MM DDDD" string. Input system inspired by @SteveEckert's similar one.

### Another form as a function, 91 bytes

```
def f(d,m,y):return sum([3,not(y%400 and not y%100 or y%4),3,2,3,2,3,3,2,3,2,3][:m])+m*28+d

```

In this case input is three integers, the month being between 0-11. This would work in Python 2 also.
> 0 votes

# Answer
# Excel, 106 bytes

```
=AND(C1>2,OR(MOD(A1,400)=0,AND(MOD(A1,4)=0,MOD(A1,100))))+30*B1-31+CHOOSE(B1,1,2,0,1,1,2,2,3,4,4,5,5,6)+C1

```

Takes input in three cells `A1` = Year, `B1` = Month, `C1` = Day.

---

```
AND(C1>2,OR(MOD(A1,400)=0,AND(MOD(A1,4)=0,MOD(A1,100))))

```

`1` if LeapYear, else `0`

```
30*B1-31+CHOOSE(B1,1,2,0,1,1,2,2,3,4,4,5,5,6)+C1

```

Multiple of `30`, CHOOSE for additional days, plus days in month

---

**Evolution:**

```
=IF(AND(C1>2,OR(MOD(A1,400)=0,AND(MOD(A1,4)=0,MOD(A1,100)))),1,0)+CHOOSE(B1,0,31,59,90,120,151,181,212,243,273,304,334,365)+C1
=IF(AND(C1>2,OR(MOD(A1,400)=0,AND(MOD(A1,4)=0,MOD(A1,100)))),1,0)+CHOOSE(B1-1,31,59,90,120,151,181,212,243,273,304,334,365)+C1
=IF(AND(C1>2,OR(MOD(A1,400)=0,AND(MOD(A1,4)=0,MOD(A1,100)))),1,0)+30*(B1-1)+CHOOSE(B1,0,1,-1,0,0,1,1,2,3,3,4,4,5)+C1
=IF(AND(C1>2,OR(MOD(A1,400)=0,AND(MOD(A1,4)=0,MOD(A1,100)))),1,0)+30*B1-30+CHOOSE(B1,0,1,-1,0,0,1,1,2,3,3,4,4,5)+C1
=IF(AND(C1>2,OR(MOD(A1,400)=0,AND(MOD(A1,4)=0,MOD(A1,100)))),1,0)+30*B1-31+CHOOSE(B1,1,2,0,1,1,2,2,3,4,4,5,5,6)+C1
=AND(C1>2,OR(MOD(A1,400)=0,AND(MOD(A1,4)=0,MOD(A1,100))))+30*B1-31+CHOOSE(B1,1,2,0,1,1,2,2,3,4,4,5,5,6)+C1

```
> 0 votes

# Answer
# Scala, 126 bytes

Port of @Neil's Javascript answer in Scala.

---

Golfed version. Try it online!

```
(y,m,d)=>d+Integer.parseInt("03479cehkmpr".toSeq(m-1).toString,36)+(m-1)*28-(if ((y%(if (y%25==0)16 else 4)!=0)&&m>1)1 else 0)

```

Ungolfed version. Try it online!

```
object Main {
  def dayOfYear(y: Int, m: Int, d: Int): Int = {
    val monthOffsets = "03479cehkmpr".toList
    d + Integer.parseInt(monthOffsets(m - 1).toString, 36) + (m - 1) * 28 - (if ((y % (if (y % 25 == 0) 16 else 4) != 0) && m > 1) 1 else 0)
  }

  def main(args: Array[String]): Unit = {
    println(dayOfYear(2016, 07, 05))  // 187
    println(dayOfYear(2000, 03, 28))  // 88
    println(dayOfYear(0666, 06, 06))  // 157
    println(dayOfYear(6789, 10, 11))  // 284
    println(dayOfYear(0004, 04, 04))  // 95
    println(dayOfYear(1337, 07, 13))  // 194
  }
}

```
> 0 votes

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


title: Calculate Euler's totient function

text:
# Question
Title: Calculate Euler's totient function
# Background

Euler's totient function `φ(n)` is defined as the number of whole numbers less than or equal to `n` that are relatively prime to `n`, that is, the number of possible values of `x` in `0 < x <= n` for which `gcd(n, x) == 1`. We've had  few totient-related challenges before, but never one which is just calculating it.

The mapping of the totient function onto the whole numbers is OEIS A000010.

# Challenge

Given an integer `n > 0`, calculate `φ(n)`. You may take input through command-line arguments, standard input, function arguments, or anything else reasonable. You may give output through standard output, return values, or anything else reasonable. Anonymous functions are acceptable. You may assume that the input will not overflow your natural method of storing integers, e.g. `int` in C, but you **must** support inputs up to 255. **If your language has a built-in totient function, you may not use it.**

# Examples

```
φ(1) => 1
φ(2) => 1
φ(3) => 2
φ(8) => 4
φ(9) => 6
φ(26) => 12
φ(44) => 20
φ(105) => 48

```

Shortest answer in bytes wins. If your language uses an encoding other than UTF-8, mention it in your answer.

# Answer
## Mathematica, ~~27~~ 22 bytes

```
Range@#~GCD~#~Count~1&

```

An unnamed function that takes and returns an integer.

Not much to explain here, except that `@` is prefix notation for function calls and `~...~` is (left-associative) infix notation, so the above is the same as:

```
Count[GCD[Range[#], #], 1] &

```
> 14 votes

# Answer
# J, 9 bytes

```
(-~:)&.q:

```

This is based on the Jsoftware's essay on totient functions.

Given *n* = *p*1*e*1*p*2*e*2 ∙∙∙ *p**k**e**k* where *p**k* is a prime factor of *n*, the totient function φ(*n*) = φ(*p*1*e*1) ∙ φ(*p*2*e*2) ∙∙∙ φ(*p**k**e**k*) = (*p*1 \- 1) *p*1*e*1 \- 1 ∙ (*p*2 \- 1) *p*2*e*2 \- 1 ∙∙∙ (*p**k* \- 1) *p**k**e**k* \- 1.

## Usage

```
   f =: (-~:)&.q:
   (,.f"0) 1 2 3 8 9 26 44 105
  1  1
  2  1
  3  2
  8  4
  9  6
 26 12
 44 20
105 48
   f 12345
6576

```

## Explanation

```
(-~:)&.q:  Input: integer n
       q:  Prime decomposition. Get the prime factors whose product is n
(   )&     Operate on them
  ~:         Nub-sieve. Create a mask where 1 is the first occurrence
             of a unique value and 0 elsewhere
 -           Subtract elementwise between the prime factors and the mask
     &.q:  Perform the inverse of prime decomposition (Product of the values)

```
> 12 votes

# Answer
# MATL, 7 bytes

```
t:Zd1=s

```

You can TryItOnline. Simplest idea, make a vector 1 to N, and taken gcd of each element with N (`Zd` does gcd). Then, find which elements are equal to 1, and sum the vector to get the answer.
> 11 votes

# Answer
## Haskell, 28 bytes

```
f n=sum[1|1<-gcd n<$>[1..n]]

```

Uses Haskell's pattern matching of constants. The tricks here are fairly standard for golfing, but I'll explain to a general audience.

The expression `gcd n<$>[1..n]` maps `gcd n` onto `[1..n]`. In other words, it computes the `gcd` with `n` of each number from `1` to `n`:

```
[gcd n i|i<-[1..n]]

```

From here, the desired output is the number of `1` entries, but Haskell lacks a `count` function. The idiomatic way to `filter` to keep only `1`'s, and take the resulting `length`, which is much is too long for golfing.

Instead, the `filter` is simulated by a list comprehension `[1|1<-l]` with the resulting list `l`. Usually, list comprehensions bind values onto variable like in `[x*x|x<-l]`, but Haskell allows a pattern to be matched against, in this case the constant `1`.

So, `[1|1<-l]` generating a `1` on each match of `1`, effectively extracting just the `1`'s of the original list. Calling `sum` on it gives its length.
> 9 votes

# Answer
## Python 2, 44 bytes

```
f=lambda n,d=1:d/n or-f(d)*(n%d<1)-~f(n,d+1)

```

Less golfed:

```
f=lambda n:n-sum(f(d)for d in range(1,n)if n%d<1)

```

Uses the formula that the Euler totients of the divisors of `n` have a sum of `n`:

The value of `ϕ(n)` can then be recursively computed as `n` minus the sum over nontrivial divisors. Effectively, this is doing Möbius inversion on the identity function. I used the same method in a golf to compute the Möbius function.

Thanks to Dennis for saving 1 byte with a better base case, spreading the initial value of `+n` into `+1` for each of the `n` loops, done as `-~`.
> 9 votes

# Answer
# Jelly, 4 bytes

```
Rgċ1

```

Try it online!

### Explanation

```
Rgċ1   Main monadic chain. Argument: z

R      Yield [1 2 3 .. z].
 g     gcd (of each) (with z).
  ċ1   Count the number of occurrences of 1.

```

## With built-in

```
ÆṪ

```

Try it online!

### Explanation

```
ÆṪ   Main monadic chain. Argument: z

ÆṪ   Totient of z.

```
> 8 votes

# Answer
# Regex (ECMAScript), 131 bytes

*At least -12 bytes thanks to Deadcode (in chat)*

```
(?=((xx+)(?=\2+$)|x+)+)(?=((x*?)(?=\1*$)(?=(\4xx+?)(\5*(?!(xx+)\7+$)\5)?$)(?=((x*)(?=\5\9*$)x)(\8*)$)x*(?=(?=\5$)\1|\5\10)x)+)\10|x

```

Try it online!

Output is the length of the match.

ECMAScript regexes make it extremely hard to count anything. Any backref defined outside a loop will be constant during the loop, any backref defined inside a loop will be reset when looping. Thus, the only way to carry state across loop iterations is using the current match position. That’s a single integer, and it can only decrease (well, the position increases, but the length of the tail decreases, and that’s what we can do math to).

Given those restrictions, simply counting coprime numbers seems impossible. Instead, we use Euler’s formula to compute the totient.

Here’s how it looks like in pseudocode:

```
N = input
Z = largest prime factor of N
P = 0

do:
   P = smallest number > P that’s a prime factor of N
   N = N - (N / P)
while P != Z

return N

```

There are two dubious things about this.

First, we don’t save the input, only the current product, so how can we get to the prime factors of the input? The trick is that (N - (N / P)) has the same prime factors \> P as N. It may gain new prime factors \< P, but we ignore those anyway. Note that this only works because we iterate over the prime factors from smallest to greatest, going the other way would fail.

Second, we have to remember two numbers across loop iterations (P and N, Z doesn’t count since it’s constant), and I just said that was impossible! Thankfully, we can swizzle those two numbers in a single one. Note that, at the start of the loop, N will always be a multiple of Z, while P will always be less than Z. Thus, we can just remember N + P, and extract P with a modulo.

Here’s the slightly more detailed pseudo-code:

```
N = input
Z = largest prime factor of N

do:
   P = N % Z
   N = N - P
   P = smallest number > P that’s a prime factor of N
   N = N - (N / P) + P
while P != Z

return N - Z

```

And here’s the commented regex:

```
# \1 = largest prime factor of N
# Computed by repeatedly dividing N by its smallest factor
(?= ( (xx+) (?=\2+$) | x+ )+ )

(?=
        # Main loop!
        (
                # \4 = N % \1, N -= \4
                (x*?) (?=\1*$)

                # \5 = next prime factor of N
                (?= (\4xx+?) (\5* (?!(xx+)\7+$) \5)? $ )

                # \8 = N / \5, \9 = \8 - 1, \10 = N - \8
                (?= ((x*) (?=\5\9*$) x) (\8*) $ )

                x*
                (?=
                        # if \5 = \1, break.
                        (?=\5$) \1
                |
                        # else, N = (\5 - 1) + (N - B)
                        \5\10
                )
                x
        )+
) \10

```

And as a bonus…

## Regex  (ECMAScript 2018, number of matches), 23 bytes

```
x(?<!^\1*(?=\1*$)(x+x))

```

Try it online!

Output is the number of matches. ECMAScript 2018 introduces variable-length look-behind (evaluated right-to-left), which makes it possible to simply count all numbers coprime with the input.

It turns out this is independently the same method used by Leaky Nun's Retina solution, and the regex is even the same length (and interchangeable). I'm leaving it here because it may be of interest that this method works in ECMAScript 2018 (and not just .NET).

```
                        # Implicitly iterate from the input to 0
x                       # Don’t match 0
 (?<!                 ) # Match iff there is no...
                 (x+x)  # integer >= 2...
         (?=\1*$)       # that divides the current number...
     ^\1*               # and also divides the input

```
> 7 votes

# Answer
## Pyke, 5 bytes

```
m.H1/

```

Try it here!

```
count(map(gcd, range(input)), 1)

```
> 6 votes

# Answer
# J, 11 bytes

```
+/@(1=+.)i.

```

## Usage

```
>> f =: +/@(1=+.)i.
>> f 44
<< 20

```

where `>>` is STDIN and `<<` is STDOUT.

## Explanation

```
+/ @ ( 1 = +. ) i.
               │
   ┌───────────┴┐
 +/@(1=+.)      i.
   │
 ┌─┼──┐
+/ @ 1=+.
    ┌─┼─┐
    1 = +.

>> (i.) 44            NB. generate range
<< 0 1 2 3 4 ... 43
>> (+.i.) 44          NB. calculate gcd of each with input
<< 44 1 2 1 4 ... 1
>> ((1=+.)i.) 44      NB. then test if each is one (1 if yes, 0 if no)
<< 0 1 0 1 0 ... 1
>> (+/@(1=+.)i.) 44   NB. sum of all the tests
<< 20

```
> 5 votes

# Answer
# Python \>=3.5, ~~76~~ ~~64~~ 58 bytes

*Thanks to LeakyNun for golfing off 12 (!) bytes.*

*Thanks to Sp3000 for golfing off 6 bytes.*

```
import math
lambda n:sum(math.gcd(n,x)<2for x in range(n))

```

I love how readable Python is. This makes sense, even through the golfedness.
> 5 votes

# Answer
# Ruby, 32 bytes

```
->n{(1..n).count{|i|i.gcd(n)<2}}

```

a lambda that takes an integer n, and returns the counts of how many integers in the range (1..n) are coprime with n.
> 5 votes

# Answer
# Perl 6,  ~~26 24~~  22 bytes

```
~~{[+] (^$^n Xgcd $n) X== 1}
{+grep 2>*,(^$_ Xgcd$_)}~~
{[+] 2 X>(^$_ Xgcd$_)}
```

### Explanation:

```
{
  [+] # reduce using &infix:<+>
    2
    X[>] # crossed compared using &infix:«>»
    (
      ^$_    # up to the input ( excludes input )
      X[gcd] # crossed using &infix:<gcd>
      $_     # the input
    )
}

```

### Example:

```
#! /usr/bin/env perl6
use v6.c;

my &φ = {[+] 2 X>(^$_ Xgcd$_)};

say φ(1) # 1
say φ(2) # 1
say φ(3) # 2
say φ(8) # 4
say φ(9) # 6
say φ(26) # 12
say φ(44) # 20
say φ(105) # 48

say φ 12345 # 6576

```
> 4 votes

# Answer
# Brachylog, 25 bytes

```
:{:1e.$pdL,?$pd:LcCdC}fl.

```

### Explanation

Brachylog has no GCD built-in yet, so we check that the two numbers have no prime factors in common.

* Main predicate:

```
:{...}fl.             Find all variables which satisfy predicate 1 when given to it as
                      output and with Input as input.
                      Unify the Output with the length of the resulting list

```
* Predicate 1:

```
:1e.                  Unify Output with a number between Input and 1
    $pdL              L is the list of prime factors of Output with no duplicates
        ,
         ?$pd:LcC     C is the concatenation of the list of prime factors of Input with
                      no duplicates and of L
                 dC   C with duplicates removed is still C

```
> 4 votes

# Answer
# Julia 1.x, 22 bytes

```
!n=sum(gcd.(1:n,n).<2)

```

This is the same as the old solution, but using newer features of the language, as the original solution dates back to something like Julia 0.4. This solution uses function broadcasting to achieve the result more efficiently.

---

# Julia, 25 bytes

```
!n=sum(i->gcd(i,n)<2,1:n)

```

It's simple - the `sum` function allows you to give it a function to apply before summing - basically the equivalent of running `map` and then `sum`. This directly counts the number of relatively prime numbers less than `n`.
> 4 votes

# Answer
# Python 2, 57 bytes

```
f=lambda n,k=1,m=1:n*(k>n)or f(n-(n%k<m%k)*n/k,k+1,m*k*k)

```

Test it on Ideone.

### Background

By Euler's product formula,

where **φ** denotes Euler's totient function and **p** varies only over prime numbers.

To identify primes, we use a corollary of Wilson's theorem:

### How it works

At all times, the variable **m** will be equal to the square of the factorial of **k - 1**. In fact, we named arguments default to **k = 1** and **m = 0!2 = 1**.

As long as **k ≤ n**, `n*(k>n)` evaluates to **0** and the code following `or` gets executed.

Recall that `m%k` will yield **1** if **m** is prime and **0** if not. This means that `x%k<m%k` will yield **True** if and only if both **k** is a prime number and **x** is divisible by **k**.

In this case, `(n%k<m%k)*n/k` yields **n / k**, and subtracting it from **n** replaces its previous value with **n(1 - 1/k)**, as in Euler's product formula. Otherwise, `(n%k<m%k)*n/k` yields **0** and **n** remains unchanged.

After computing the above, we increment **k** and multiply **m** by the "old" value of **k2**, thus maintaining the desired relation between **k** and **m**, then call **f** recursively with the updated arguments.

Once **k** exceeds **n**, `n*(k>n)` evaluates to **n**, which is returned by the function.
> 4 votes

# Answer
# Python 2, 44 bytes

```
lambda n:sum(k/n*k%n>n-2for k in range(n*n))

```

This uses the same method to identify coprimes as my answer to “Coprimes up to N”.

Try it online!
> 4 votes

# Answer
# Pyth, 6 bytes

```
smq1iQ

```

Try it online!

```
/iLQQ1

```

Try it online!

## Explanation

```
smq1iQ     input as Q
smq1iQdQ   implicitly fill variables

 m     Q   for d in [0 1 2 3 .. Q-1]:
    iQd        gcd of Q and d
  q1           equals 1? (1 if yes, 0 if no)
s          sum of the results

/iLQQ1     input as Q

 iLQQ      gcd of each in [0 1 2 3 .. Q-1] with Q
/    1     count the number of occurrences of 1

```
> 3 votes

# Answer
## PowerShell v2+, 72 bytes

```
param($n)1..$n|%{$a=$_;$b=$n;while($b){$a,$b=$b,($a%$b)};$o+=!($a-1)};$o

```

PowerShell doesn't have a GCD function available to it, so I had to roll my own.

This takes input `$n`, then ranges from `1` to `$n` and pipes those into a loop `|%{...}`. Each iteration we set two helper variables `$a` and `$b` and then execute a GCD `while` loop. Each iteration we're checking that `$b` is still non-zero, and then saving `$a%$b` to `$b` and the previous value of `$b` to `$a` for the next loop. We then accumulate whether `$a` is equal to `1` in our output variable `$o`. Once the for loop is done, we place `$o` on the pipeline and output is implicit.

As an example of how the `while` loop works, consider `$n=20` and we're on `$_=8`. The first check has `$b=20`, so we enter the loop. We first calculate `$a%$b` or `8%20 = 8`, which gets set to `$b` at the same time that `20` gets set to `$a`. Check `8=0`, and we enter the second iteration. We then calculate `20%8 = 4` and set that to `$b`, then set `$a` to `8`. Check `4=0`, and we enter the third iteration. We calculate `8%4 = 0` and set that to `$b`, then set `$a` to `4`. Check `0=0` and we exit the loop, so the *GCD(8,20)* is `$a = 4`. Thus, `!($a-1) = !(4-1) = !(3) = 0` so `$o += 0` and we don't count that one.
> 3 votes

# Answer
# Factor, 50 bytes

```
[ dup iota swap '[ _ gcd nip 1 = ] filter length ]

```

Makes a range (*iota*) **n**, and *curries* **n** into a function which gets **gcd x n** for all values of **0 \<= x \<= n**, tests if the result is **1**. *Filter* the original range on whether the result of **gcd x n** was **1**, and take its *length*.
> 3 votes

# Answer
# Japt `-mx`, ~~7~~ 5 bytes

```
yN ¥1

```

Run it online

-2 bytes thanks to Shaggy
> 3 votes

# Answer
# C (gcc), ~~67~~ 65 bytes

```
f(x,a,b,y,z){for(z=y=x;a=y--;z-=b>1)for(b=x;a^=b^=a^=b%=a;);x=z;}

```

Try it online!

Edit: Removed temp variable.

Edit2: -1 thanks to @HowChen

Slightly less golfed

```
f(x,a,b,y,z){
  // counts y NOT coprime with x and subtract
  for(z=y=x;a=y--;z-=b>1)
    // compute GCD
    for(b=x;a^=b^=a^=b%=a;);
  x=z;
}

```
> 3 votes

# Answer
# Retina, ~~36~~ 29 bytes

7 bytes thanks to Martin Ender.

```
.+
$*
(?!(11+)\1*$(?<=^\1+)).

```

Try it online!

## Explanation

There are two stages (commands).

### First stage

```
.+
$*

```

It is a simple regex substitution, converting the input to that many ones.

For example, `5` would be converted to `11111`.

### Second stage

```
(?!(11+)\1*$(?<=^\1+)).

```

This regex tries to match the positions which satisfy the condition (co-prime with input), and then return the number of matches.
> 2 votes

# Answer
## 05AB1E, 7 bytes

```
Lvy¹¿i¼

```

**Explained**

```
Lv        # for each x in range(1,n)
  y¹¿     # GCD(x,n)
     i¼   # if true (1), increase counter
          # implicitly display counter

```

Try it online
> 2 votes

# Answer
# Haskell, ~~31~~ 30 bytes

```
\n->sum[1|x<-[1..n],gcd n x<2]

```

*1 byte saved, thanks to @Damien.*

Selects values with gcd = 1, maps each to 1, then takes the sum.
> 2 votes

# Answer
**Common Lisp, 58 bytes**

```
(defun o(x)(loop for i from 1 to x if (=(gcd x i)1)sum 1))

```

This is a simple loop which counts up 1 to the given n and increments the sum if gcd = 1. I use the function name o since t is the true boolean value. Not nearly the shortest but fairly simple.
> 2 votes

# Answer
# MATLAB / Octave, 21 bytes

```
@(n)sum(gcd(n,1:n)<2)

```

Creates an anonymous function named `ans` which can be called with the integer `n` as the only input: `ans(n)`

**Online Demo**
> 2 votes

# Answer
# APL, 7 bytes

```
+/1=⊢∨⍳

```

This is a monadic function train that takes an integer on the right. The approach here is the obvious one: sum (`+/`) the number of times the GCD of the input and the numbers from 1 to the input (`⊢∨⍳`) is equal to 1 (`1=`).

Try it here
> 2 votes

# Answer
# JavaScript (ES6), 53 bytes

```
f=(n,k=n)=>k--&&(C=(a,b)=>b?C(b,a%b):a<2)(n,k)+f(n,k)

```

Try it online!
> 2 votes

# Answer
# Brachylog v2, 16 bytes

```
{>ℕ≜;?ḋˢ{⊇ᵛ!}Ė}ᶜ

```

Try it online!

```
{             }ᶜ    Count the number of possible ways that:
  ℕ≜                some non-negative integer
 >                  less than the input
    ;?              and the input
      ḋˢ            have prime factorizations
        {⊇ᵛ!}       the largest shared subset of which
             Ė      is empty.

```

# Brachylog v2, 16 bytes

```
⟨⟦₅zg⟩{ḋˢ⊇ᵛ!Ė}ˢl

```

Try it online!

```
   z                Cycling zip
 ⟦₅                 the range from 0 to one less than the input
⟨   g⟩              with a list containing only the input.
      {      }ˢ     Map where possible over the pairs:
       ḋˢ           the prime factorizations'
         ⊇ᵛ!        largest shared subset
            Ė       is empty.
               l    For how many pairs did it succeed?

```

A nuance that my explanations fail to capture is that  fails given an input of 1, so if `ḋˢ` is given a list containing 1, the 1 is essentially discarded and ignored--so the `⊇ᵛ!` (which is really "find any common subset, then discard all of this predicate's choice points", hence the braces in the first solution) of the remaining single number is its entire prime factorization, decidedly not empty, unless the list was nothing but 1s in which case everything is empty.
> 2 votes

# Answer
# Husk, 7 bytes

```
ṁo=1⌋¹ḣ

```

Try it online!

```
ṁo=1⌋¹ḣ
ṁ     ḣ     # sum of function applied to 1..input
 o          # join 2 functions:
    ⌋¹      # greatest common divisor with input
  =1        # equals 1

```
> 2 votes

# Answer
# Actually, 11 bytes

```
;╗R`╜g`M1@c

```

Try it online!

### Explanation

```
;╗R`╜g`M1@c   register stack             remarks

                       44
;                      44 44
 ╗            44       44
  R           44       [1 2 3 .. 44]
       M      44       10                for example
    ╜         44       10 44
     g        44       2
              44       [1 2 1 .. 44]     gcd of each with register
        1     44       [1 2 1 .. 44] 1
         @    44       1 [1 2 1 .. 44]
          c   44       20                count

```

## With built-in

Try it online!
> 1 votes

# Answer
## JavaScript (ES6), 67 bytes

```
f=n=>[...Array(n)].reduce(r=>r+=g(n,++i)<2,i=0,g=(a,b)=>b?g(b,a%b):a)

```
> 1 votes

# Answer
## Batch, ~~151~~ ~~145~~ 144 bytes

```
@echo off
set t=
for /l %%i in (1,1,%1)do call:g %1 %%i
echo %t%
exit/b
:g
set/ag=%1%%%2
if not %g%==0 call:g %2 %g%
if %2%==1 set/at+=1

```

Edit: Saved 4 bytes by removing unnecessary spaces. Saved 1 byte by using `+=`. Saved 1 byte by clearing `t` as `+=` will interpret that as `0` anyway. Saved 1 byte thanks to @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ.
> 1 votes

# Answer
# Pari/GP, 24 bytes

```
n->sum(i=1,n,gcd(i,n)<2)

```

Try it online!
> 1 votes

# Answer
# TI-84 BASIC, 19 bytes

```
Prompt A:sum(seq(1=gcd(A,B),B,1,A

```
> 1 votes

# Answer
# Japt `-mx`, 2 bytes

```
jN

```

Try it here
> 1 votes

# Answer
# JavaScript (Node.js), 42 bytes

```
n=>(g=k=>k&&((k/n|0)*k%n>n-2)+g(k-1))(n*n)

```

Try it online!

Direct port of Dennis' solution (*\<- also see the explanation in that answer*) to JavaScript.

Alternatives:

```
n=>(g=k=>k&&g(k-1)+!(~((k/n|0)*k)%n))(n*n)
n=>(g=k=>k&&g(k-1)+!(((k/n|0)*k-1)%n))(n*n)
n=>(g=k=>k&&g(k-1)+!((k/n|0)*k%n-n+1))(n*n)
f=(n,k=0)=>k<n*n&&((k/n|0)*k%n>n-2)+f(n,k+1)

```
> 1 votes

# Answer
# Vyxal `s`, 5 bytes

```
ɾ$ġ1=

```

Try it Online!

No totient builtin

Inclusive range, swap with input, gcd, equal to 1, sum
> 1 votes

# Answer
# Thunno 2 `L`, 3 bytes

```
æĠḅ

```

Try it online!

#### Explanation

```
æĠḅ  # Implicit input
æ    # Filter by:
 Ġ   #  GCD with input
  ḅ  #  Equals one?
     # Length of list
     # Implicit output

```
> 1 votes

# Answer
## Hoon, 56 bytes

```
|=
a/@
(lent (skim (gulf 1 a) |=(@ =(1 d:(egcd +< a)))))

```

Measure the length of the list \[1...a\] after keeping all the elements where GCD(i, a) == 1
> 0 votes

# Answer
# Arturo, 34 bytes

```
$->n[enumerate..1n'x->2>gcd@[x,n]]

```

Try it
> 0 votes

# Answer
# \>\<\> (Fish), 76 bytes

```
0i::?v~~n;
v&~$1\:&:&:&%?v$:&:&%?
/~v?:-2&      <
r \1+\20.
1.   \6
\+r1-20.

```

Try it
> 0 votes

# Answer
# SageMath, 41 bytes

Run it on SageMathCell!

```
f=lambda n:sum(gcd(i,n)<2 for i in[1..n])

```
> 0 votes

# Answer
# Nekomata, 4 bytes

```
RG1Ĉ

```

Attempt This Online!

```
RG1Ĉ
R       Range from 1 to input
 G      GCD
  1Ĉ    Count 1s

```
> 0 votes

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