title: Find the largest banknote

text:
# Question
Title: Find the largest banknote
Banknotes in many countries come in denominations of 1,2,5,10,20,50,100,200,500,1000, etc. That is, one of \\$ \\{ 1,2,5\\} \\$ times a power of \\$10\\$. This is OEIS A051109, except we'll extend the sequence to bigger values.

Given a positive integer as the input, the program should output the largest bank note that is less than or equal to the input. The input will be less than \\$2^{63}\\$.

Examples:

```
1 => 1
2 => 2
3 => 2
5 => 5
9 => 5
42 => 20
49 => 20
50 => 50
99 => 50
100 => 100
729871 => 500000
3789345345234 => 2000000000000
999999999999999999 => 500000000000000000

```

# Answer
# Python 2, 39 bytes

```
f=lambda n:n>9and 10*f(n/10)or 5>>5/-~n

```

Try it online!
> 15 votes

# Answer
# Perl 5 `-p`, ~~24~~ ~~20~~ 19 bytes

*Credit to @DomHastings for shortening this entry.*

```
s/\B./0/g;y;3-9;225

```

Try it online!
> 12 votes

# Answer
# Python 2, 38 bytes

```
lambda a,*b:`5>>5/-~int(a)`+"0"*len(b)

```

Try it online!

A function that takes in the number as characters, and returns a numeric string.

Use xnor's formula to get from a digit to 1, 2, or 5.
> 9 votes

# Answer
# Raku, 30 bytes

```
{first /^(1|2|5)0*$/,($_...1)}

```

Try it online!

Counts down from the input, finding the first number that is a 1,2 or a 5 followed by only zeroes
> 7 votes

# Answer
# , 26 bytes

```
(>:{:@#])1 2 5*<.&.(10&^.)

```

Try it online!

### How it works

```
(>:{:@#])1 2 5*<.&.(10&^.)                             250
                   (10&^.) logarithm to base 10          3.x
               <.&.        and floor                     3
                   (10&^.) and reverse the logarithm:  100
         1 2 5*            1 2 5 times that:   100 200 500
(>:     )                  input greater-equal list? 1 1 0
      #]                   take from list:         100 200
   {:@                     last element                200

```
> 7 votes

# Answer
# , ~~51~~ 47 bytes

Golfed down 4 bytes by Giuseppe.

```
function(x,z=c(5,2,1)*10^nchar(x)/10)z[z<=x][1]

```

Try it online!
> 6 votes

# Answer
# Rockstar, 187 bytes

```
Listen to B
cast B at 0 into C
D is 5
E is 2
F is 1
let G be F
if C is as strong as E
let G be E

if C is as strong as D
let G be D

while B is as strong as 10
let B be B over 10
let G be G of 10

say G

```

Ungolfed and a bit more Rockstarish (yes this is valid syntax)

```
sunset was spellbound
god was a roundabout

Listen to the devil
cast the devil at sunset into the storm

(The kids are young don't let em grow up too fast)
Tommy is 5
Jimmy is 2
Alice is 1

(My kids are my heroes)
let my Hero be Alice

if the storm is as strong as Jimmy
let my Hero be Jimmy

if the storm is as strong as Tommy
let my Hero be Tommy

while the devil is as strong as god
let the devil be the devil over god
let my hero be my hero of god

say my hero

```

First time ever using this language, just having a bit of fun
> 6 votes

# Answer
# Charcoal, 12 bytes

```
⭆Ｓ∧¬κ÷⁵⊕÷⁵⊕ι

```

Try it online! Link is to verbose version of code. Explanation:

```
 Ｓ             Convert input to a string
⭆              Map over digits and join
    κ           Current index
   ¬            Is zero
  ∧             Boolean AND
           ι    Current digit
          ⊕     Incremented
         ⁵      Literal 5
        ÷       Integer divide
       ⊕        Incremented
      ⁵         Literal 5
     ÷          Integer divide
                Implicitly print

```
> 5 votes

# Answer
# Husk, ~~6~~ 5 bytes

```
Ω£İ₅←

```

Try it online!

## Explanation

It's basically a built-in.

```
Ω£İ₅←   Implicit input.
    ←   Decrement
Ω       until
 £      is an element of
  İ₅    Infinite list of powers of 10 and multiples by 2 or 5:
            [1,2,5,10,20,50,100,200,500,..]

```

Here's a more interesting 10-byte solution that avoids `İ₅`:

```
Ωö€Ḋ10d↔d←

```

Try it online! Explained:

```
Ωö€Ḋ10d↔d←   Implicit input.
         ←   Decrement
Ω            until
 ö           composition of 4 functions:
        d     number to digits,
       ↔      reverse,
      d       back to number,
  €           is an element of
   Ḋ          list of divisors of
    10        10 (so 1, 2, 5 or 10, and the last one is impossible).

```
> 5 votes

# Answer
# Japt, ~~12~~ 10 bytes

I/O as an integer.

```
@AvXìw}aaU

```

Try it

---

## Alternative (w/ `-m` flag), 10 bytes

I/O as a string or an array of digits. Credit, again, to xnor for the formula to find the first digit.

```
V?T:5Á5/°U

```

Try it

---

## Original (with `-h` flag), 12 bytes

I/O as integer strings.

```
#}ì úTUl)f§U

```

Try it

```
#}ì úTUl)f§U     :Implicit input of integer string U
#}               :125
  ì              :To digit array
    ú            :Right pad each
     T           :  With 0
      Ul         :  To the length of U
        )        :End padding
         f       :Filter
          §U     :  Less than or equal to U
                 :Implicit output of last element

```
> 4 votes

# Answer
# Pyth, ~~26 bytes~~ 21 bytes

```
efgQTm*d^Ttl+Qk[1 2 5

```

Try it online!

*Old Solution:*

```
V60 aY*h^%N3 2^T/N3;efgQTY

```

Explanation:
Using `((n % 3) ** 2 + 1) * 10**int(n/3)` To calculate a the banknote for n in the series.

```
V60 aY*h^%N3 2^T/N3;efgQTY
V60                         Looping 60 times.
      *h^%N3 2^T/N3         Calculate the current iterations banknote value
    aY                      Append it to list Y
                     fgQTY  Filter the list for all values less than or equal to input
                    e       Grab the last value in the list.

```

Try it online!
> 4 votes

# Answer
# JavaScript, 34 bytes

```
f=n=>n<2?1:n<5?2:n<10?5:10*f(n/10)

```

Try it online!

A recursive function that checks each denomination, otherwise divides by 10 and tries again.

Note that the last test case fails because it exceeds the maximum safe integer.

-6 bytes don't need to check `<1`
> 4 votes

# Answer
# APL (Dyalog Unicode), 17 bytes

```
10⊥≢↑'125'(⍎⍸⊃⊣)⊃

```

Try it online!

A tacit function that takes input as a string, and returns an integer. `⎕FR←1287` is needed to get exact results for high numbers.

### How it works

```
10⊥≢↑'125'(⍎⍸⊃⊣)⊃  ⍝ Input: a string of digits without leading zeros
                ⊃  ⍝ First char
     '125'( ⍸  )   ⍝ Interval index into '125'; 1→1; 2-4→2; 5-9→3
             ⊃⊣    ⍝ The char at the above index of '125'
           ⍎       ⍝ Eval it, so it becomes numeric
   ≢↑              ⍝ Pad with zeros to the length of the input
10⊥                ⍝ Convert from base 10 digits to integer

```
> 4 votes

# Answer
# Husk, 14 bytes

```
:ḟ≤←¹s521mK'0t

```

Try it online!

This is my first Husk answer.

In Haskell this would look like

```
\x -> (find (<= head x) (show 521)) : (map (const '0') (tail x))

```
> 4 votes

# Answer
# JavaScript (V8), 62 bytes

```
n=>(e=Math.log10(n)|0,x=n/(y=10**e),y*((x>=5)*5||(x>=2)*2||1))

```

Try it online!
> 3 votes

# Answer
# Retina 0.8.2, 15 bytes

```
T`3-9`225
\B.
0

```

Try it online! Link includes test cases. Explanation:

```
T`3-9`225

```

Change `3` and `4` to `2`, and higher digits to `5`.

```
\B.
0

```

Change all digits after the first to `0`.
> 3 votes

# Answer
# brainfuck, ~~78 69~~ 66 bytes

```
-[<+>>+>+<<-----],++<[->-<]>[-[-[-[>+++<[-]]]]>+<]>--.>--->,[<.>,]

```

Try it online!

-9 bytes by rearranging the variables and adding the output directly to the ASCII value.

-3 bytes by calculating and triplicating the constants in a single loop

```
[tape: 51, input (of first digit), output + 51, 51, input (of other digits)]
-[<+>>+>+<<-----]       51 0 51 51
,++<[->-<]              input minus 49("1")
>[                      if not input = 1
  -[-[-[                    if not input between 2 and 4
    >+++                        add 3 to output (will add another 1 later)
    <[-]                        set input = 0
  ]]]                       exit if
  >+<                       inc output ("4" if input between "2" and "4" | "7" if input not between "1" and "4")
]
>--.                    decrement output by 2 and print it
>---                    set third 51 to 48("0")
>,[                     while more characters in input
  <.>                       print "0"
  ,                         read next input char
]

```
> 3 votes

# Answer
# 05AB1E, ~~13~~ ~~12~~ ~~10~~ 9 bytes

```
LR.ΔRTÑQO

```

-2 bytes by porting *@JoKing*'s Raku answer, so make sure to upvote him as well!
-1 byte by taking inspiration from *@Zgarb*'s second Husk answer.

Try it online or verify almost all test cases (times out for the larger test cases).

**Explanation:**

```
L          # Push a list in the range [1, (implicit) input-integer]
 R         # Reverse it
  .Δ       # Find the first value which is truthy for:
    R      #  Reverse the integer
           #   i.e. 200 → "002"
     T     #  Push 10
      Ñ    #  Pop 10 and push its divisors: [1,2,5,10]
       Q   #  Check for each if it's equal to the reversed integer
           #   "002" → [0,1,0,0]
        O  #  Take the sum of those checks (only 0 or 1 will be truthy at a time,
           #  and 10 is never truthy because no integer had leading 0s)
           # (after which the result is output implicitly)

```
> 3 votes

# Answer
# Rockstar, ~~163~~ ... ~~119~~ ~~117~~ 97 bytes

```
listen to N
cut N
roll N in D
X's 5
until X's as low as D
let X be/2
turn down X

say X*10*N or X

```

Try it (Code will need to be pasted in)
> 3 votes

# Answer
# C (gcc), ~~40 39~~ 32 bytes

```
f(n){n=n>9?10*f(n/10):5>>5/-~n;}

```

Try it online!

Recursively calls itself, multiplying the returned value by \\$10\\$ and chopping the last digit off \\$n\\$ until \\$n\\$ is \\$9\\$ or less. Then returns one of \\$\\{1,2,5\\}\\$, whichever lays just below or equal to \\$n\\$ using xnor's formula.
> 2 votes

# Answer
# Wolfram Language (Mathematica), 45 bytes

```
Max@Select[{1,2,5}10^⌊Log10[s=#]⌋,#<=s&]&

```

Try it online!
> 2 votes

# Answer
# sed 4.2.2, 25

* Thanks to @David258 for suggesting the use of `2g` to start replacing at the 2nd match and saving a byte.

Pretty much the same as the perl answer. Sadly the sed `y` command is not as flexible.

```
s/./0/2g
y/346789/225555/

```

Try it online!
> 2 votes

# Answer
# Brain-Flak, 116 bytes

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

```

Try it online!

This uses string IO. Meaning input is expected as a string and output is produced as a string. This works by replacing all the digits other than the lead with zeros and then mapping the lead to the three results.

Rather predictably for Brain-Flak the two biggest sinks are

1. Producing the ascii code for `0`
2. Mapping 9 different values to arbitrary outputs.

The first part which replaces everything with zeros is:

```
({}<<>(((((()()()){}){}){}){})<>{{}<>(({}))<>}>)

```

With most of it being the code for point 1:

```
(((((()()()){}){}){}){})

```
> 2 votes

# Answer
# JavaScript, ~~30~~ 29 bytes

I/O as an array of digits.

Uses xnor's formula for the first digit so please be sure to upvote him if you're upvoting this.

```
a=>a.map((x,y)=>y?0:5>>5/-~x)

```

Try it online!
> 1 votes

# Answer
# Pip, 25 bytes

```
@(_<=aFI[5 2o]*t**(#a-1))

```

A simple solution with filtering.

## Explanation

```
@(_<=aFI[5 2o]*t**(#a-1))
               t**(#a-1)  ten to the power (length of input - 1)
        [5 2o]*           times the list [5,2,1]
  _<=aFI                  Filtered by lambda: element <= input?
@(                      ) first element of filtered list

```

Try it online!
> 1 votes

# Answer
# Octave, 43 bytes

```
@(x)y((y=[5 2 1]*10^floor(log10(x)))<=x)(1)

```

Try it online!

This converts the number to the highest power of 10 less than the number, then multiplies by 5, 2, and 1 to get the possible notes that could be involved. It then finds the largest note still less than the number.

---

It should be noted that Octave is very doubley and not really friends with 64bit integers. As a result numbers larger than 2^53 don't reliably work due to double precision issues. This may invalidate the answer.

---

---

The below answer is valid only if it is allowed to take the input as a string, and return a string, overcoming the double precision issues.

# Octave, 41 bytes

```
@(x,y='521')[y(x(1)>=y)(1) 48+x(2:end)*0]

```

Try it online!
> 1 votes

# Answer
# Bash, ~~39~~ 36 bytes

Saved 3 bytes thanks to Digital Trauma!!!

```
echo $[(5>>5/-~${1::1})*10**~-${#1}]

```

Try it online!

Port of my C answer.

### Explanation:

```
echo $[(5>>5/-~${1::1})*10**~-${#1}]
     $[                            ]   # Evaluate what's inside as an
                                       #   arithmetic expression
       (5>>                            # Shift 5 to the right by
           5/                          #   5 integally divided by
             -~                        #     1 plus
               ${1                     #      the first argument's
                  ::1})                #        substring starting at 0 of length 1
                       *               # Times
                        10**           #   10 to the power of
                              ${#1}    #     the length of the first agument
                            ~-         #       minus 1

```
> 1 votes

# Answer
# x86-16 machine code, IBM PC DOS, ~~34~~ ~~31~~ 30 bytes

```
00000000: d1ee ad8a c849 b830 0acd 10ac 3c35 7c04  .....I.0....<5|.
00000010: b035 eb07 3c32 b032 7d01 48cd 29c3       .5..<2.2}.H.).

```

Listing:

```
D1 EE       SHR  SI, 1          ; SI to DOS PSP
AD          LODSW               ; AL = input length
8A C8       MOV  CL, AL         ; input length into CL
49          DEC  CX             ; remove leading space from length
B8 0A30     MOV  AX, 0A30H      ; AH = 0AH, AL = '0'
CD 10       INT  10H            ; display '0' CX number of times
AC          LODSB               ; AL = first digit
3C 35       CMP  AL, '5'        ; is it less than five?
7C 04       JL   LT_FIVE        ; if so, check two
B0 35       MOV  AL, '5'        ; otherwise it's a 5 spot
EB 07       JMP  DONE           ; jump to display
        LT_FIVE:
3C 32       CMP  AL, '2'        ; is it less than two?
B0 32       MOV  AL, '2'        ; if not, it's a 2
7D 01       JGE  DONE           ; jump to display
48          DEC  AX             ; otherwise it's a '1'
        DONE:
CD 29       INT  29H            ; display first digit of denomination

C3          RET                 ; return to DOS

```

Try it online! (type `ASM 1`, `ASM 9`, etc)

Looks at the first digit and determines if it's less than `5` or `2` and resets it to the appropriate note digit. Then displays the remaining length of the input string as `0`'s.

Standalone PC DOS executable COM program. Input via command line, output to console.
> 1 votes

# Answer
# Brachylog, 25 bytes

```
{≥.~×Ċ{~^h10}ᵗh∈125∧≜}ᵘot

```

Try it online!

### How it works

```
{≥.~×Ċ{~^h10}ᵗh∈125∧≜}ᵘot
{                    }ᵘ   find all unique outputs of …
 ≥.                         the output is less-equal the input,
   ~×Ċ                      and two numbers which product is the output, where
      {~^h10}ᵗ                the 2. number can be obtained by 10^k,
              h∈125           the 1. number is one of 1, 2, 5
                   ∧≜       return the output with the constrains solved
                       ot order all possible banknotes and take the largest

```
> 1 votes

# Answer
# Thunno 2 `t`, 5 bytes

```
ærTFƇ

```

Try it online!

Note: this is pretty slow (the 729871 case takes ~5s on my computer and ~10s on the online interpreter) because it checks every number in the range \\$\[1 .. \text{input}\]\\$.

#### Explanation

```
ærTFƇ  # Implicit input
æ      # Filter [1..input] by:
 r     #  Reverse it
  TF   #  Push the factors of 10
       #   -> [1, 2, 5, 10]
    Ƈ  #  And check if the reversed
       #  integer is in this list
       # Implicit output of last
       # (largest) integer

```
> 1 votes

# Answer
# Jelly, 9 bytes, slow

```
DUḌ⁵%
’Ç¿

```

Try it online!

```
’Ç¿     Decrement input while…

DUḌ     The number with digits reversed (12300 → 321)
   ⁵%   is not a divisor of 10 (10 % n is truthy).

```

# Jelly, 11 bytes, fast

```
DḢRg⁵ṀṁDŻIḌ

```

Try it online!

```
DḢR           range [1..first digit]
   g⁵         gcd each with 10
     Ṁ        maximum
      ṁD      reshape like original digits (e.g. [2,2,2,2,2])
        ŻI    prepend 0, get increments (e.g. [2,0,0,0,0])
          Ḍ   digits to number

```

This uses the fact that mapping \\$\[1 \dots 9\]\\$ to \\$\[1,2,2,2,5,5,5,5,5\]\\$ is achieved by $$ n \mapsto \max\_{1 \leq k \leq n} \gcd(k, 10). $$

Porting xnor's `5>>5/-~n` formula is six bytes `‘5:5æ»`, but the above is only four `Rg⁵Ṁ`.
> 1 votes

# Answer
# \>\<\>, 41 bytes

```
1$:a(?v:a%-a,$a*!
&v?=1:/~$?)4&52
 <;n *<

```

Try it Online!

The first line is a loop, bringing down the number to a single digit through the usual `:a%-a,` process. At the same time, the magnitude is transferred to another number on the stack.

As always, branching gets verbose, and with no floor function, two conditionals are needed.
> 0 votes

# Answer
# Befunge-93, 58 bytes

```
~:"4"`!#v_"5">,~1+#v_@
v     >#< "2"^"0"  <
>"1"`#^_  "1"^

```

Try it online!

## How does it work?

(This is essential the same as Xcali's second Perl solution)

We first look at the first character, if it's greater than `4`, we print `5`, if it's greater than `1` we print `2`, else we print `1`. Then, for each following character on the input, we print a 0:

```
~:"4"`!#v_"5">,        # If the first character is greater than 4, print a 5

~:"4"`!#v_   >,        # If the first character isn't greater than 4,
v     >#< "2"^         # but is greater than 1, print a 2
>"1"`#^_

~:"4"`!#v_   >,        # If the first character isn't greater than 4,
v     >#<    ^         # and isn't greater than 1, print a 1
>"1"`#^_  "1"^

>,~1+#v_@              # In a loop (mind, the loop is entered at the ~)
^"0"  <                # for each character on the input, print a 0;
                       # terminate the program when there is no more input.

```
> 0 votes

# Answer
# SimpleTemplate 0.84, 76 bytes

Yeah, it is ... big ...
One of the longest answers here, but it works!

It uses a simple lookup variable, to know which digit to show.
Then, a simple regular expression separates the first digit and the rest.
A loop just writes out all the zeroes needed.

```
{@setX"1122255555"}{@ifargv.0 matches"@(\d)(.*)@"M}{@echoX.[M.1]}{@eachM.2}0

```

Notice that the input can be a number or a string: it will be handled as a string anyway. But be aware of PHP's integer precision.

---

**Ungolfed:**

To make it a bit more readable, here's an ungolfed version:

```
{@set initial_digit 1, 1, 2, 2, 2, 5, 5, 5, 5, 5}
{@if argv.0 matches "@(\d)(.*)@" match}
    {@echo initial_digit.[match.1]}
    {@each match.2 as digit}
        {@echo 0}
    {@/}
{@/}

```

Consideration points:

* `initial_digit` can be a string or an array, as both can have their elements indexed the same way.
* `match.0` isn't used because it has the whole matched input, while `match.1` and `match.2` have the content of their respective groups.
* `{@echo 0}` and `0` have the exact same function: output `0`.
Any non-whitespace and all characters that arent in a valid instructions are outputted directly.
* `{@each match.2 as digit}` and `{@eachM.2}` loop over all characters in `match.2` or `M.2`, being a lot shorter than a `repeat`.
* To convert to a function, just wrap it in an `{@fn ...}[...]{@/}`.
For the golfed version, all missing `{@/}` **must** be added for the code to work properly.

---

You can try this on: http://sandbox.onlinephpfunctions.com/code/a45b85003e2d495c796046b000326fb1b5e50423
> 0 votes

# Answer
# \>\<\>, 25 bytes

```
i\{c%:4)3*$1)++>n<
?\i0(:

```

Try it online!
> 0 votes

# Answer
# Desmos, 50 bytes

```
d=[5,2,1]
a=10^{\floor(\log n)}
f(n)=ad[d<=n/a][1]

```

Try it on Desmos!

Finds the greatest value in \\$\[1,2,5\]\\$ less than the first digit of \\$n\\$ and multiplies it by \\$10^{\lfloor\log\_{10}n\rfloor}\\$
> 0 votes

---
Tags: code-golf, sequence
---


title: Prepend line number comments

text:
# Question
Title: Prepend line number comments
**Definitions**:

* A *line* is a possibly empty sequence of characters terminated by a “newline character.” A “newline character” is a character that cannot be a component of the aforementioned character sequence.
* A *line number comment* is a character sequence that does not alter the meaning of source code in the programming language of your submission. It *contains* a decimal representation of the (integral) unique line number associated with the line of input. (A conventional notation is sufficient, e. g. `4.2E1` for `42`.)
* A *content line* is a line that conveys meaning in the programming language of your submission.

**Task**:

* Write a program (or function) that numbers all lines, but *at least* all content lines. The program shall *print* a line number comment followed by the respective processed (otherwise unaltered) input line. The function shall *return* a value accordingly.

**Conditions**:

* Numbered lines must be numbered in ascending order in the order of input (i. e. not in the order a processor for the respective programming language might possibly process the input).
* Line numbers must be consecutive. That means you may not omit numbers.
* The first line is identified either by the line number zero (`0`) or one (`1`). The behavior must be consistent for all possible input.
* Line numbers must reproduce: Feeding the output back as input again produces the same line numbers.

**Accommodations**:

* You *may* assume that input is valid source code in your submission’s programming language.
* You *may* assume that no token is spread across multiple lines (e. g. multiline string literals or backslash-continuation), thus insertion of a line number comment is guaranteed not to alter the source code’s meaning.
* You *may* assume input consists of lines. Numbering of non-lines (that is empty input or input not terminated by a newline-character) is implementation-dependent.

**Test cases**:

C (note that tabulator characters are preserved):

```
#include <stdio.h>
int main()
{
    char c;
    c = getchar();
    do
    {
        putchar(c);
    }
    while (c);
}

```

```
/* 0*/#include <stdio.h>
/* 1*/int main()
/* 2*/{
/* 3*/  char c;
/* 4*/  c = getchar();
/* 5*/  do
/* 6*/  {
/* 7*/      putchar(c);
/* 8*/  }
/* 9*/  while (c);
/*10*/}

```

Pascal (note that it is not specified that input *is* indeed source code):

```
Esolanging fruit is hanging low.

```

```
{           1 }Esolanging fruit is hanging low.

```

If you input that output back in again, it must reproduce the same line number comments:

```
{           1 }{           1 }Esolanging fruit is hanging low.

```

SQL (note that only content lines were numbered):

```
-- populate foo with some data
insert into foo values (1, 'bar');
insert into foo values (2, 'foobar');

select * from foo;

```

```
-- populate foo with some data
/*0*/insert into foo values (1, 'bar');
/*1*/insert into foo values (2, 'foobar');

/*2*/select * from foo;

```

# Answer
## Pyke, 7 bytes

```
o\Kz++r

```

Try it here!

```
o       -  o++
 \K     -  "K"
   z    -  input()
    ++  - sum(^)
      r - while no errors: GOTO start

```

I'm declaring integer comments to be the integer followed by the character `K` and then the line. An extra byte is used to stop the newline opcode from kicking in and printing an extra thing.
> 5 votes

# Answer
# Perl, 8+1 = 9 bytes

```
say"#$."

```

Run with `-p` (1 byte penalty). (Note to people unfamiliar with PPCG rules; you also need to specify a modern version of Perl syntax using `-M5.010`, but we decided that options to select language versions are free and don't incur a byte penalty, so I didn't mention it in the original version of this post.)

`-p` places the program into an implicit loop; it basically causes the program to become a filter that processes each line separately (i.e. the entire program is run on the first line, then the second, then the third, and so on). Perl also keeps track of a line number, called `$.`, that records how many lines of input have been read. So all the program's doing is letting `-p` read a line of input; output a `#`, the current line number (`$.`), and a newline (`say` adds a newline by default, which is helpful in this case, and is also shorter than the more commonly seen `print`); and then letting `-p` output the original line of code that it read (typically a program using `-p` would do some sort of processing on the input, but because we didn't, it's just output unchanged). Comments in Perl run from `#` to a newline (the `#` in the program itself doesn't start a comment because it's inside a string literal), so what we're basically doing is taking the opportunity to write comment lines into the file as we process it, without disturbing the "natural" read and write cycle of `-p`.
> 16 votes

# Answer
# Javascript, ~~43~~ 39 bytes

```
a=>a.replace(/^/gm,_=>`/*${++b}*/`,b=0)

```

Thanks to ETH and Conor for saving 4 bytes.
> 9 votes

# Answer
# , 10 bytes

```
O:1òYjjP

```

Try it online!
> 5 votes

# Answer
# Lua, ~~80~~ 75 Bytes

*Saved some bytes by abusing the langauge.*

```
x=1print("--[[1]]"..(...):gsub("\n",load('x=x+1return"\\n--[["..x.."]]"')))

```

Simple enough starter answer.

## Ungolfed, +

```
x=1                                                     -- Assign x to 1...
print(                                                  -- Print...
      "--[[1]]"                                         -- The first line number comment...
      ..                                                -- With...
      (...):gsub(                                       -- The input, replacing all...
                 "\n",                                  -- Newlines...
                    load                                -- with a string compiled function...
                    (' \
                    x=x+1                               --Increment x by one... \
                    return"\\n--[["..x.."]]"            -- And return the new linecomment. \
                    ')
                 )
      )

```
> 4 votes

# Answer
## Batch, 91 bytes

```
@set n=
@for /f "delims= tokens=*" %%a in (%1) do @set/an+=1&call echo @rem %%n%%&echo %%a

```

Batch doesn't have a way of reading STDIN until EOF, so instead the file name has to be passed as a command-line parameter.
> 3 votes

# Answer
# Gema, ~~16~~ 15 characters

```
*\n=\!@line\n$0

```

In Gema there are only line comments, starting with `!`.

Sample run:

```
bash-4.3$ cat l33t.gema
e=3
g=9
i=1
o=0
t=7

bash-4.3$ gema -f l33t.gema <<< 'Hello World!'
H3ll0 W0rld!

bash-4.3$ gema '*\n=\!@line\n$0' < l33t.gema > l33t-nr.gema

bash-4.3$ cat l33t-nr.gema
!1
e=3
!2
g=9
!3
i=1
!4
o=0
!5
t=7

bash-4.3$ gema -f l33t-nr.gema <<< 'Hello World!'
H3ll0 W0rld!

```

The following are to answer Adám's question, whether is possible to add the line number in kind of ignored code.

Gema code is essentially a collection of *from*=*to* transformation rules, or *template*=*action* in Gema terms. I see no way to define a *template* that will never ever match anything, this alone not seems to be the way.

## Gema, 18 characters

```
*\n=c:\=@line\;:$0

```

Transforms `e=3` into `c:=1;:e=3`.

Luckily in Gema there are *domains*, kind of namespaces. The above code defines the dummy rules in namespace c, that we never use. Unfortunately a mentioned domain remains in effect until the end of line, so we have to explicitly to switch back to default domain.

## Gema, 18 characters

```
*\n=@line\=\$0\;$0

```

Transforms `e=3` into `1=$0;e=3`.

A less complicated alternative is to use effectless code instead of ignored one. I mean to put back exactly what was matched.
> 3 votes

# Answer
# Kotlin extension function, 69 60 bytes

`fun String.a()=lines().mapIndexed{i,s->"/*$i*/$s"}.joinToString("\n")`

`fun String.a(){lines().mapIndexed{i,s->println("/*$i*/$s")}}`

Example usage:

```
fun main(args: Array<String>) {
  //language=kotlin
  val code = """fun main(args: Array<String>) {
  println("Hello world!")
}"""
  code.a()
}

```

Output:

```
/*0*/fun main(args: Array<String>) {
/*1*/  println("Hello world!")
/*2*/}

```
> 3 votes

# Answer
## awk (~~19~~ 13 bytes)

**19 bytes** : This insert "#"+line number above each line of code

```
{print"#"NR"\n"$0}

```

**13 bytes** : Credit & thanks to @manatwork for two 13 bytes solution

As `1` action defaults to `print $0`:

```
{print"#"NR}1

```

Or by replacing `$0` content

```
$0="#"NR RS$0

```
> 3 votes

# Answer
# BASH (+ GNU sed) 27 bytes

```
sed 'i#
='|sed 'N;s/\n//;N'

```

The first part (`i#` `\n` `=`) almost works in GNU sed (for 4 bytes), but it puts a newline after the `#`.
> 2 votes

# Answer
# APL (Dyalog Unicode), 53 bytes

```
N←(⍴P)[0]⋄P←((2×N)⍴0 1)⍀P⋄P[2×⍳N;]←⊂[1](N⍴'⍝'),[.5]⍳N

```

Try it on TryAPL.org!

The environmental variable ⎕IO←0. The program to comment is contained in an (n 1) nested array of string statements. The result is returned in the same (expanded) array.
> 2 votes

# Answer
# CJam, 21 Bytes

I am not well-versed in CJam at all, but I knew for a fact it has comments :)

```
qN%ee{"e#"o(oNo(oNo}/

```

Explanation coming soon.
> 1 votes

# Answer
# Mathematica, 58 bytes

```
i = 1; StringReplace[#, StartOfLine :> "(*" <> ToString@i++ <> "*)"] &

```
> 1 votes

# Answer
# jq, 31 characters

(27 characters code + 4 characters command line options.)

```
"#\(input_line_number)\n"+.

```

In jq there are only line comments, starting with `#`.

Sample run:

```
bash-4.3$ cat l33t.jq
gsub("e";"3")|
gsub("g";"9")|
gsub("i";"1")|
gsub("o";"0")|
gsub("t";"7")

bash-4.3$ jq -Rr -f l33t.jq <<< 'Hello World!'
H3ll0 W0rld!

bash-4.3$ jq -Rr '"#\(input_line_number)\n"+.' l33t.jq > l33t-nr.jq

bash-4.3$ cat l33t-nr.jq
#1
gsub("e";"3")|
#2
gsub("g";"9")|
#3
gsub("i";"1")|
#4
gsub("o";"0")|
#5
gsub("t";"7")

bash-4.3$ jq -Rr -f l33t-nr.jq <<< 'Hello World!'
H3ll0 W0rld!

```
> 1 votes

# Answer
# C# 6, ~~66~~ 63 bytes

Thanks to CSharpie

~~(666, devils code ^^)~~ not any more ...

This works for all languages using "C style comments" (C, C++, C#, Java, ....)

It simply splits the string into lines, prepends every line with its index and joins the edited lines again with new line characters.

```
s=>string.Join("\n",s.Split('\n').Select((l,i)=>$"/*{i}*/"+l));

```

old version:

```
s=>string.Join("\n",s.Split('\n').Select((l,i)=>$"/*{i,3}*/{l}"));

```
> 1 votes

# Answer
# GolfScript, 23 Bytes

```
n/0:i;{"#"i):i+n+\+}%n*

```

There are only line comments starting with "#".

Ungolfed & explained:

```
           # the input is pushed on the stack automatically
n          # n is a predefined variable for "\n"
/          # splits the input string with the previously pushed "\n" as delimiter
0:i;       # i = 0
{          # A code block: It is used for map here (going through the input)
    "#"    # push a "#" onto the stack
    i):i  # save i + 1 in i, the value is again not popped from the stack
    +      # implicitly converts the number i to a string and concatenates "#" with it
    n      # newline
    +      # add a newline (# introduces a *line* comment)
    \      # switch the top to elements (-> yields the comment as the bottom, and the line as the top element on the stack)
    +      # concatenate them
}          # end of the code block
%          # map
n          # newline
*          # join the list with newlines between them
           # outputs are done implicitly

```

I am pretty sure that this can be further simplified, especially the `i` can probably be left out.

You can test it here: https://golfscript.apphb.com/ Because this site doesn't support adding inputs, you'll have to put a string surrounded with double quotes in front of the code. `'\n'` will be a newline. Be aware of the fact, that there are other escape sequences as well. User `'\\'` if you are not sure.
> 1 votes

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

Revisited this question and found a shorter solution. It saves a few bytes to append `//` comments instead prepending `/**/` ones.

```
a=>a.replace(/$/gm,_=>"//"+v++,v=1)

```

Try it online!

# JavaScript, 47 bytes

Old answer:

```
a=>a.split`
`.map((l,i)=>"/*"+i+"*/"+l).join`
`

```
> 1 votes

# Answer
# C (gcc), 54 bytes

```
a;main(i){for(;gets(&a);)printf("/*%d*/%s\n",i++,&a);}

```

Try it online!

Why not
> 1 votes

# Answer
## Python 2, 82 bytes

Works for space-only indentation

```
for i,l in enumerate(input().split('\n')):print l.split(l.lstrip())[0]+'#%d\n'%i+l

```

Indentation-less version for 56 bytes

```
for x in enumerate(input().split('\n')):print'#%d\n%s'%x

```
> 0 votes

# Answer
# Nim, 52 bytes

```
var n=0
for l in stdin.lines:n+=1;echo "#[",n,"]#",l

```

Attempt This Online!

Nim is indentation-sensitive, but it doesn't seem to have a problem with comments before indentation.
> 0 votes

# Answer
# Haskell, 84 bytes

Assumes each indentation is done by a horizontal tab(`\t`).

```
unlines.zipWith(\n l->let(x,y)=span('\t'==)l in x++"{-"++show n++"-}"++y)[0..].lines

```
> 0 votes

# Answer
## Pascal, 198 bytes

* This is a full Pascal `program` as per ISO standard 10206 “Extended Pascal.” Pascal does not permit multiline literals. String and character literals spanning multiple lines are explicitly banned. Therefore there is no problem with that.
* The `program` only works correctly for up to `maxInt + 1` input lines (zero-based indexing). `MaxInt` is an implementation-defined value. There is no safeguard installed when exceeding this limit.
* A *line* is a possibly empty sequence of characters *terminated* by a special “end of line character.” This `program` might possibly number *non-lines*, too. At any rate *empty* input is not numbered.

```
program p(input,output);var n:integer;c:char;begin n:=0;while not EOF do begin write('{',n,'}');repeat read(c);write(c)until EOF or_else EOLn;if not EOF then begin writeLn;read(c)end;n:=n+1 end end.

```

Expanded and annotated:

```
program prependLineNumberComment(input, output);
    var
        { Contains the currently processed `input` line number. }
        lineNumber: integer value 0;
        { Identifiers of buffer variables (`input↑`, `output↑`) are too long. }
        c: char;
    begin
        while not EOF do
        begin
            write('{ ', lineNumber, ' }');
            lineNumber ≔ succ(lineNumber);

            { Copy `input` to `output`. }
            repeat
            begin
                { This is equivalent to: `c ≔ input↑; get(input);`: }
                read(c);
                { This is equivalent to: `output↑ ≔ c; put(output);`: }
                write(c);
            end
            { Invoking `EOLn(input)` if `EOF(input)` is `true` is fatal. }
            until EOF or_else EOLn;

            { `get(input)` requires that `EOF(input)` is `false`. }
            if not EOF then
            begin
                { The only valid method for producing a newline character is: }
                writeLn;
                { Advance reading cursor for the embracing `while`‑loop. }
                read(c);                    { Shorter than `get(input);` }
            end;
        end;
    end.

```
> 0 votes

---
Tags: code-golf, code-generation, comment
---


# Question
Title: Pen Pineapple Apple Pen... with your own pens, pineapples and apples
# Prelude:

This challenge is different from "another cat program".
There's literal tons of different twists, why can't I have my own, people?
Unique things:

* It isn't reading direct input to output.
* It is manipulating the string in a way that for sure isn't a straight-up cat.

# Challenge:

Given 3 inputs (or one input, separated however you like) get three objects (words) that we're going to substitute for pens, pineapples and apples in the lyrics and output.

## Output format (according to lyrics found on AZLyrics):

Assuming (replace values with brackets with these):

* A, B, C with input words (ex. `apple`)
* UA, UB, UC with input words with uppercase first letters (if not uppercase already) (ex. `Apple`)
* FUA, FUB, FUC with respectively first uppercase letters: (ex. `A`)
* a/an with article respective to first letter vowel/consonant (ex. `an`)

```
[FUA]-[FUB]-[FUC]-[FUA]

I have [a/an] [A], I have [a/an] [C].
Uh! [UC]-[UA]!

I have [a/an] [A], I have [a/an] [B].
Uh! [UB]-[UA]!

[UC]-[UA], [UB]-[UA].
Uh! [UA]-[UB]-[UC]-[UA].
[UA]-[UB]-[UC]-[UA]!
```

# Test case:

Test with `pen`, `pineapple` and `apple`:

```
P-P-A-P

I have a pen, I have an apple.
Uh! Apple-Pen!

I have a pen, I have a pineapple.
Uh! Pineapple-Pen!

Apple-Pen, Pineapple-Pen.
Uh! Pen-Pineapple-Apple-Pen.
Pen-Pineapple-Apple-Pen!

```

# Rules:

* If input doesn't start with a letter, assume consonant (`a`) and first uppercase the first character (ex. `123 -> 1`).
* , lowest amount of characters wins!

# Answer
> 10 votes
## JavaScript (ES6), ~~217~~ ... ~~187~~ 183 bytes

Takes input as an array of 3 strings, such as `['pen', 'pineapple', 'apple']`.

```
a=>`0-1-2-0

6, 895-3!

6, 794-3!

5-3, 4-393-4-5-3.
3-4-5-3!`.replace(/\d/g,n=>[u=(w=a[n%3])[0].toUpperCase(),u+w.slice(1),`I have a${~'AEIOU'.search(u)?'n':''} `+w,`.
Uh! `][n/3|0])

```

### Examples

```
let f =

a=>`0-1-2-0

6, 895-3!

6, 794-3!

5-3, 4-393-4-5-3.
3-4-5-3!`.replace(/\d/g,n=>[u=(w=a[n%3])[0].toUpperCase(),u+w.slice(1),`I have a${~'AEIOU'.search(u)?'n':''} `+w,`.
Uh! `][n/3|0])

console.log(f(['pen', 'pineapple', 'apple']));
console.log(f(['golf', 'puzzle', 'code']));
```

# Answer
> 4 votes
## Perl 6, 165 bytes

```
{"0-3-6-0

2, 897-1!

2, 594-1!

7-1, 4-191-4-7-1.
1-4-7-1!".subst: /\d/,->$x {((.tc.comb[0],.tc,"I have a{'n' if /:i^<[aeiou]>/} $_" for $_),".
Uh! ").flat[$x]},:g}

```

Uses the same approach as Arnauld's JS answer.

# Answer
> 3 votes
# Python 3.6 \- ~~351~~ ~~287~~ 286 bytes

```
def x(a,b,c):t=(a,b,c);p,q,r=('a'+'n'*(i[0]in'aeiouAEIOU')for i in t);A,B,C=map(str.title,t);print(f"""{A[0]}-{B[0]}-{C[0]}-{A[0]}

I have {p} {a}, I have {r} {c}.
Uh! {C}-{A}!

I have {p} {a}, I have {q} {b}.
Uh! {B}-{A}!

{C}-{A}, {B}-{A}.
Uh! {A}-{B}-{C}-{A}.
{A}-{B}-{C}-{A}!""")

```

There is nothing fancy here except making use of the new feature of string literal formatting.

```
Input:
s('golf','puzzle','code')

```

```
Output:
G-P-C-G

I have a golf, I have a code.
Uh! Code-Golf!

I have a golf, I have a puzzle.
Uh! Puzzle-Golf!

Code-Golf, Puzzle-Golf.
Uh! Golf-Puzzle-Code-Golf.
Golf-Puzzle-Code-Golf!

```

**Note** \- The version is `3.6` where string literal formatting was introduced. Hence, this won't work in earlier versions.

# Answer
> 3 votes
## Batch, ~~494~~ 490 bytes

```
@echo off
set s=%1
set t=%2
set u=%3
call:u %s:~,1%- %t:~,1%- %u:~,1%- %s:~,1%
echo(
call:h %1 %3
call:u Uh! %3- %1!
echo(
call:h %1 %2
call:u Uh! %2- %1!
echo(
call:u %3- %1, %2- %1.
call:u Uh! %1- %2- %3- %1.
call:u %1- %2- %3- %1!
exit/b
:h
set s=I have a %1, I have a %2.
for %%v in (a e i o u)do call set s=%%s:a %%v=an %%v%%
echo %s%
exit/b
:u
set s= %*
for %%u in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)do call set s=%%s: %%u= %%u%%
echo%s:- =-%

```

Explanation: The `:h` subroutine handles the line `I have a %, I have a %.` The `%`s are substituted from the appropriate command-line arguments, and then the strings `a a`, `a e`, `a i`, `a o` and `a u` are replace with the equivalent `an` version. The `:u` subroutine handles the other lines; it takes the parameter words, and upper cases all the first letters. (An extra space is prefixed to allow the first word to be upper cased, but it is removed on output.) To handle words after `-`s, extra spaces are passed, but they are also deleted on output. The `:u` subroutine is also used for the first line, although extracting the initials is awkward.

# Answer
> 1 votes
# Lua, ~~615~~ 607 bytes

*Saved 8 bytes thanks to \[an anonymous user\]*

*Whew, long one. Try it here.*

```
w=io.read a,b,c=w(),w(),w()function d(u)if ("aeiouAEIOU"):find(z(u))~=nil then return "an" else return "a" end end function z(y)return y:sub(1,1):upper()end f=z(c)..c:sub(2).."-"..z(a)..a:sub(2).."-"..z(b)..b:sub(2).."-"..z(a)..a:sub(2)print(z(a).."-"..z(b).."-"..z(c).."-"..z(a).."\n\nI have "..d(a).." "..a..", I have "..d(c).." "..c..".\nUh! "..z(c)..c:sub(2).."-"..z(a)..a:sub(2).."!\n\nI have "..d(a).." "..a..", I have "..d(b).." "..b..".\nUh! "..z(b)..b:sub(2).."-"..z(a)..a:sub(2).."!\n\n"..z(c)..c:sub(2).."-"..z(a)..a:sub(2)..", "..z(b)..b:sub(2).."-"..z(a)..a:sub(2)..".\nUh! "..f..".\n"..f.."!")

```

*I am 100% certain this can be shortened. I am just lazy..*

Basically uses **a lot** of string manipulation. There are 3 main functions and one variable:

* `d(string)`: returns an if string is vowel (`AEIOUaeiou`), else returns a
* `z(string)`: returns the first letter in uppercase
* `z(s) .. s:sub(2)`: returns whole word, but first letter uppercase
* `f`: the end word (in a variable, to save some bytes). In your test case, it would be `Pen-Pineapple-Apple-Pen`.

## Input: `pen`, `pineapple`, `apple`

## Output:

```
P-P-A-P

I have a pen, I have an apple.
Uh! Apple-Pen!

I have a pen, I have a pineapple.
Uh! Pineapple-Pen!

Apple-Pen, Pineapple-Pen.
Uh! Pen-Pineapple-Apple-Pen.
Pen-Pineapple-Apple-Pen!
```

# Answer
> 1 votes
# Python 2, 283 bytes

```
a=input()
r='0-1-2-0\n\n9 3, 9 5.\nUh! 8-6!\n\n9 3, 9 4.\nUh! 7-6!\n\n8-6, 7-6.\nUh! 6-7-8-6.\n6-7-8-6!'
for j in range(10):r=r.replace(str(j),([i[:1].upper()for i in a]+[['a ','an '][1+'aeiouAEIOU'.find(i[:1])/9]+i for i in a]+[i[:1].upper()+i[1:]for i in a]+['I have'])[j])
print r

```

Try it online!

# Answer
> 0 votes
# TypeScript's Type System, 348 bytes

```
//@ts-nocheck
type P<S>=Capitalize<S>
type U<S>=P<S extends`${infer A}${any}`?A:S>
type N<S>=`I have a${U<S>extends"A"|"E"|"I"|"O"|"U"?"n":""} ${S}`
type F<A,B,C,D=P<A>,E=P<B>,F=P<C>,G=`${D}-${E}-${F}-${D}`>=`${U<A>}-${U<B>}-${U<C>}-${U<A>}

${N<A>}, ${N<C>}.
Uh! ${F}-${D}!

${N<A>}, ${N<B>}.
Uh! ${E}-${D}!

${F}-${D}, ${E}-${D}.
Uh! ${G}.
${G}!`

```

Try it at the TypeScript playground!

Composes helper types to avoid repeating as much code as possible, then uses them in a type `F<A,B,C>`.

Explanation:

```
type P<S>=Capitalize<S>   // alias the built-in to uppercase the first
                          // letter of a string type, since it is
                          // used a lot.

type U<S>=.               // to get the initial of the string, we
  P<S extends             // capitalize the result of matching against
    `${infer A}${any}`    // a string-type to match the first letter
      ?A                  // select that letter to capitalize
      :S>                 // unless the match failed somehow.

type N<S>=                // to get the "I have [a/an] [S]" bit, we
  `I have a${             // take "I have a" and
    U<S>extends           // check if the initial of the word matches
      "A"|"E"|"I"|"O"|"U" // an uppercase vowel
        ?"n":""           // if it does, insert "n", otherwise ""
  } ${S}`                 // finally, we append a space and the word.

type F<A,B,C,             // take the three words A, B, and C
  D=P<A>,E=P<B>,F=P<C>,   // assign D, E, F to A, B, C capitalized
  G=`${D}-${E}-${F}-${D}` // assign G to the "Pen-Pineapple-Apple-Pen"
>=
`${U<A>}-${U<B>}-${U<C>}-${U<D> /* the P-P-A-P bit */}

${N<A>}, ${N<C> /* I have a pen, I have an apple */}.
Uh! ${F}-${D /* Apple-Pen */}!

${N<A>}, ${N<B> /* I have a pen, I have a pineapple. */}.
Uh! ${E}-${D /* Pineapple-Pen */}!

${F}-${D /* Apple-Pen */}, ${E}-${D /* Pineapple-Pen */}.
Uh! ${G /* Pen-Pineapple-Apple-Pen */}.
${G /* Pen-Pineapple-Apple-Pen */}!`

```

---
Tags: code-golf, string
---


# Question
Title: Calculating π using the Gregory Leibniz series until n terms
> based off my previous challenge, this wikipedia article, and a Scratch project

Your task: given `i`, calculate \\$\pi\\$ till `i` terms of the Gregory-Leibniz series.

The series:

$$\pi=\frac{4}{1}-\frac{4}{3}+\frac{4}{5}-\frac{4}{7}+\frac{4}{9}-...$$

Here, `4/1` is the first term, `-4/3` is the second, `4/5` is the second and so on.

Note that for the nth term,

* $$\text S\_n = \frac{4 \times (-1)^{n+1}}{2n-1}$$
* $$\pi\_n = \text S\_1 + \text S\_2 + ... + \text S\_n,$$ where \\$\pi\_n\\$ is \\$\pi\\$ approximated to \\$n\\$ terms.

Test cases:

```
In - Out
1 - 4
2 - 2.66666667
3 - 3.46666667
4 - 2.8952381

```

Floating point issues are OK.

You may not calculate infinite terms of pi using this as we are calculating a number rather than terms of a series here.

This is , so shortest answer wins!

**EDIT:** It's strange that this question got some new... activity.

# Answer
# Jelly, 8 bytes

```
RḤ’4÷Ṛḅ-

```

A monadic Link that accepts a positive integer, \\$n\\$, and yields a floating point number, \\$\pi\_n\\$.

**Try it online!**

### How?

```
RḤ’4÷Ṛḅ- - Link: positive integer, n
R        - range n           -> [1,2,3,...,n]
 Ḥ       - double            -> [2,4,6,...,2n]
  ’      - decrement         -> [1,3,5,...,2n-1]
   4     - 4
    ÷    - divide            -> [4/1,4/3,4/5,...,4/(2n-1)]
     Ṛ   - reverse           -> [4/(2n-1),...,4/5,4/3,4/1]
       - - -1
      ḅ  - convert from base -> (-1)^(n-1)*4/(2n-1)+...+1*4/5+-1*4/3+1*4/1 = pi_n

```
> 4 votes

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

```
L·<z··R®β

```

-5 bytes porting *@JonathanAllan*'s Jelly answer

Try it online or verify all test cases.

**Original 14 bytes answer:**

```
0λè®N>m4*N·</+

```

Try it online or verify the infinite sequence.

**Explanation:**

```
L          # Push a list in the range [1, (implicit) input]
 ·         # Double each value: [2,4,6,...,2n]
  <        # Decrease each by 1: [1,3,5,...,2n-1]
   z       # Calculate 1/z for each: [1,1/3,1/5,...,1/(2n-1)]
    4*     # Multiply by 4: [4,4/3,4/5,...,4/(2n-1)]
      R    # Reverse the list: [4/(2n-1),...,4/5,4/3,4]
       ®β  # Convert it from a base-(-1) list to a base-10 integer:
           #  (-1)^(n-1)*4/(2n-1) + ... + 1*4/5 + -1*4/3 + 1*4/1
           # (after which the result is output implicitly)

```

The 14-byter is pretty similar as my 05AB1E answer of the previous challenge.

```
 λ         # Start a recursive environment,
  è        # to calculate a(input)
           # (which is output implicitly afterwards)
0          # Start with a(0)=0
           # Where every following a(n) is calculated by:
           #  (implicitly push the previous term a(n-1))
   ®N>m    #  Push (-1) to the power (n+1)
       4*  #  Multiply it by 4
   N·<     #  Push 2n-1
   /       #  Divide the earlier 4*(-1)**(n+1) by this (2n-1)
    +      #  Add it to the previous term a(n-1)

```
> 5 votes

# Answer
# Python 3, ~~36~~ 35 bytes

```
f=lambda n,k=1:n and 4/k-f(n-1,k+2)

```

Try it online!

-1 thanks to Mukundan314.
> 5 votes

# Answer
# , ~~31~~ 28 bytes

*Edit: -3 bytes thanks to @Dominic van Essen.*

```
\(n,m=2*1:n-1)sum(4i/1i^m/m)

```

Attempt This Online!

Uses $$ (-1)^{n+1} = -1 \times (-1)^{n} = i^2\times i^{-2n} = i^{-2n+2} = i \times i^{-(2n-1)}$$ And then $$\text S\_n = \frac{4 \times (-1)^{n+1}}{2n-1} = \frac{\frac{4i}{i^{2n-1}} }{2n-1} $$
> 5 votes

# Answer
# C (gcc), ~~63~~ 60 bytes

```
float f(n){float m=4,p=1,d=1;for(;n--;d+=2,m=-m)p+=m/d;--p;}

```

Try it online!

*Saved 3 bytes thanks to jdt!!!*
> 4 votes

# Answer
# Excel, ~~51~~ 48 bytes

Saved 3 bytes thanks to some clever math from JvdV

```
=LET(s,SEQUENCE(A1),SUM((8*ISODD(s)-4)/(2*s-1)))

```

Input is in the cell A1. Output is wherever the formula is.

* `LET(s,SEQUENCE(A1)` defines `s` to be an array of numbers from 1 to the value in A1. This is what lets us calculate the first *n* terms.
* `(8*ISODD(s)-4)` creates an array of the same sized filled with `4, -4, 4, -4, ...`. The only trick is that `ISODD()` returns a boolean and Excel turns TRUE into 1 and FALSE into 0 when you force it to do math. That means it becomes an array of `8-4, 0-4, 8-4, 0-4, ...` which then simplifies as shown above.
* `(2*s-1)` creates an array of the same size filled with `1, 3, 5, 7, ...`
* `SUM((~)/(~))` divides the first array by the second (giving us each term in the sequence) and then adds them up.
> 4 votes

# Answer
# Python 3, ~~41~~ 39 bytes

```
f=lambda x:x and(x%2*4-2)/(x-.5)+f(x-1)

```

Try it online!
> 3 votes

# Answer
# Desmos, 30 bytes

```
f(n)=∑_{k=1}^n4(-1)^k/(1-2k)

```

Pretty self-explanatory.

Try It On Desmos!

Try It On Desmos! - Prettified
> 3 votes

# Answer
# Japt `-mx`, 11 bytes

```
4*JpU /(UÑÄ

```

Try it

## Without Flags, 11 bytes

```
Ç±Z4/°ZÃÔìJ

```

Try it

```
4*JpU /(UÑÄ     :Implicit map of each U in the range [0,input)
4*              :Multiply 4 by
  J             :-1
   pU           :Raised to the power of U
      /(        :Divide by
        UÑ      :U times 2
          Ä     :Plus 1
                :Implicit output of sum of resulting array

```

```
Ç±Z4/°ZÃÔìJ     :Implicit input of integer U
Ç               :Map each Z in the range [0,U)
 ±Z             :  Increment Z by itself
   4/           :  Divide 4 by
     °Z         :  Z, prefix incremented
       Ã        :End map
        Ô       :Reverse
         ì      :Convert from digit array in base
          J     :  -1

```
> 3 votes

# Answer
# Vyxal , 10 bytes

```
4ÞNÞ∞d‹/¦i

```

Try it Online!

```
4          # 4
 ÞN        # [4, -4, 4, -4, 4, -4...
   Þ∞      # [1, 2, 3, 4, 5, 6...
     d     # [2, 4, 6, 8, 10, 12...
      ‹    # [1, 3, 5, 7, 9, 11...
       /   # [4/1, -4/3, 4/5, -4/7...
        ¦  # Take the cumulative sums of that
         i # Index the input into that

```
> 3 votes

# Answer
# Haskell, 28 bytes

```
f n=foldr((-).(2/))0[1/2..n]

```

Try it online!
> 3 votes

# Answer
# Vyxal , 13 bytes

Flag  prints out rationals in their decimal form

```
ƛ4nd‹/un›e*;∑

```

Try it Online!

**Explanation:**

```
ƛ4nd‹/un›e*;∑
ƛ          ;    Map trough range of input
 4nd‹/          Divide four by 2n-1
      un›e*     Raise -1 to the n+1 and multiply
            ∑   Sum the fractions

```

Another 13 byter: `ƛ4nd‹/k-ni*;∑`
> 2 votes

# Answer
# Factor \+ `koszul math.unicode`, 51 bytes

```
[ [1,b] [ dup 1 + -1^ 4 * swap 2 * 1 - / ] map Σ ]

```

Try it online!

* `[1,b] [ ... ] map Σ` Map each integer in 1..input using `[ ... ]` and add them together.
* `dup 1 + -1^ 4 * swap 2 * 1 - /` Just a straight translation of $$\text S\_n = \frac{4 \times (-1)^{n+1}}{2n-1}$$ Here's how the data stack looks arriving at the second term to add together:

```
       ! 2
dup    ! 2 2
1      ! 2 2 1
+      ! 2 3
-1^    ! 2 -1
4      ! 2 -1 4
*      ! 2 -4
swap   ! -4 2
2      ! -4 2 2
*      ! -4 4
1      ! -4 4 1
-      ! -4 3
/      ! -1-1/3

```
> 2 votes

# Answer
# Fortran (GFortran), 60 bytes

```
function a(j)
do i=1,j
a=a+4.0*(-1)**(i+1)/(2*i-1)
enddo
end

```

Try it online!

Mostly just exploiting implicit typing so no need to declare variable types. Also saves 1 byte by removing the space between end and do.
> 2 votes

# Answer
# Husk, ~~10~~ 9 bytes

*-1 thanks to a clever rearrangement by Dominic van Essen*

```
Ḟ`-↑M/İ14

```

Try it online!

### Explanation

Husk's reversed operand order for subtraction really hurts here, but at least Dominic found a nice workaround for the reversed division.

```
Ḟ`-↑M/İ14
      İ1   Infinite list of positive odd numbers
        4  Integer 4
    M      For each element in the first argument,
     /     divide the second argument by it
   ↑       Take the first N elements, where N is the program's argument
Ḟ          Right-fold the resulting list
 `-        on subtraction

```
> 2 votes

# Answer
# C (gcc), 47 bytes

```
float f(n){return--n?(4.-n%2*8)/(n-~n)+f(n):4;}

```

Try it online!
> 1 votes

# Answer
# APL (Dyalog Unicode), 18 bytes SBCS

```
(4×¯1*⍳)+.÷(1+2×⍳)

```

Try it on APLgolf!

A tacit function.
> 1 votes

# Answer
# Charcoal, 14 bytes

```
ＩΣＥＮ×Ｘ±¹ι∕⁴⊕⊗ι

```

Try it online! Link is to verbose version of code. Explanation:

```
   Ｎ            Input `n` as a number
  Ｅ             Map over implicit range
       ¹        Literal integer `1`
      ±         Negated
     Ｘ          Raised to power
        ι       Current value
    ×           Multiplied by
          ⁴     Literal integer `4`
         ∕      Divided by
             ι  Current value
            ⊗   Doubled
           ⊕    Incremented
 Σ              Take the sum
Ｉ               Cast to string
                Implicitly print

```
> 1 votes

# Answer
# Haskell, 36 bytes

```
f i=g[1,3..i*2]
g(h:t)=4/h-g t
g[]=0

```

Try it online!

I think it's quite self descriptive due to Haskell feature of describing something.

I try to visualize what *g* does, pretty simple : taking a list of *i* denominators but all positive...

```
[1,      3,      5,      7]
                       4/7
               4/5 -  (4/7)
 4 - ( 4/3 - ( 4/5 -  (4/7)))

hence the signs result alternating
 4 -   4/3 +   4/5 -   4/7

```
> 1 votes

# Answer
# Wolfram Language (Mathematica), 26 bytes

```
Tr[4I^#/I/#&[2Range@#-1]]&

```

Try it online!

Unnamed function that takes a positive integer argument and returns an exact fraction (the TIO footer shows both the output fraction and its decimal equivalent). Managed to beat the super straightforward `Sum[-4(-1)^j/(2j-1),{j,#}]&` by one byte by using powers of the complex unit `I` instead of powers of `-1`.
> 1 votes

# Answer
# Raku, 26 bytes

```
[\+] (4,-*...*)Z/(1,3...*)

```

Try it online!

This is an expression for the infinite sequence of partial sums.

* `(4, -* ... *)` is the sequence 4, -4, 4, -4, ....
* `(1, 3 ... *)` is the sequence 1, 3, 5, ....
* `Z/` zips those two sequences together using division.
* `[\+]` produces the sequence of partial sums.
> 1 votes

# Answer
# x86 32-bit machine code, 23 bytes

```
D9 EE D9 E8 D9 E8 D8 C0 DC E9 D8 F1 DE E2 E2 F4 DD D8 D8 C0 D9 E1 C3

```

Try it online!

Following the `fastcall` calling convention, this takes a number `n` in ECX and returns the sum of the first `n` terms on the FPU register stack.

This code creates −2/1, −2/3, −2/5, ..., and combines them using the reverse-subtract instruction. This is equivalent to negating the running total before adding each term; this handles the alternating signs, but leaves the result with the wrong sign for odd `n`, which is corrected for by taking the absolute value at the end (because all the correct results are positive). The value is also doubled at the end.

In assembly:

```
                        # Example execution for i=2
                        # FPU register stack (left is bottom):
f:  fldz                # 0
    fld1                # 0   1
r:  fld1                # 0   1   1
    fadd st(0), st(0)   # 0   1   2
    fsub st(1), st(0)   # 0  -1   2
    fdiv st(0), st(1)   # 0  -1  -2/1
    fsubrp st(2), st(0) # -2/1  -1
    loop r              #[The loop executes again:
                        # -2/1  -1   1
                        # -2/1  -1   2
                        # -2/1  -3   2
                        # -2/1  -3  -2/3
                        # -2/3+2/1  -3            ]
    fstp st(0)          # -2/3+2/1
    fadd st(0), st(0)   # -4/3+4/1
    fabs                # -4/3+4/1   (but for odd n, this fixes the sign)
    ret

```
> 1 votes

# Answer
# BQN, 9 bytes

```
-´4÷1+2×↕

```

Try it at BQN online!

### Explanation

```
-´4÷1+2×↕
        ↕  Range [0, n)
      2×   Double each number
    1+     Add 1 to each number
  4÷       Divide 4 by each number
-´         Right fold on subtraction

```
> 1 votes

# Answer
# Rust, 62 bytes

```
fn f(n:f32,k:f32)->f32{if n==0.{return 4./k}4./k-f(n-1.,k+2.)}

```

Try it online!
> 1 votes

# Answer
# MATLAB, 34 bytes

```
f=@(n)sum(4./[1:4:2*n,-(3:4:2*n)])

```

An anonymous function that makes an array of \[ 1 5 9 ... -3 -7 -11 ...\], member-wise divides 4 by the array and then sums the result.

Test:

```
arrayfun(f, 1:4)
  ans = 4.0000    2.6667    3.4667    2.8952

```
> 1 votes

# Answer
## Math++, 49 bytes

```
?>x
1>a
1>b
k+b*4/a>k
a+2>a
-b>b
x-1>x
4+5*!x>$
k

```
> 1 votes

# Answer
# \>\<\>, 33 bytes

```
0$\~n;
(?\:2%2*1-4*$:}2*1-,+$1-:1

```

Try it online
> 1 votes

# Answer
# TI-Basic, 22 bytes

```
sum(4/seq((1-2I)(-1)^I,I,1,Ans

```

Takes input in `Ans`. The first `-` is the subtraction sign, and the second is the negative sign. Only works for inputs less than or equal to 999, or 99 on a TI-83. For larger inputs, use this:

### 29 bytes

```
Input N
For(I,1,N
Ans+4(-1)^I/(1-2I
End
Ans

```

The first `-` is the negative sign, and the second is the subtraction sign. Assumes being run on fresh/RAM cleared calculator.
> 1 votes

# Answer
# APL (Dyalog Unicode), 10 bytes

```
4×-/÷1+2×⍳

```

Try it on TryAPL.org!

The environmental variable ⎕IO←0.

A tacit function.
> 1 votes

# Answer
# Pyth, 11 bytes

```
*4smc^_1dhy

```

Test suite

##### Explanation:

```
*4smc^_1dhy   | Full code
*4smc^_1dhydQ | with implicit variables
--------------+
   m        Q | For each d from 0 to input:
    c^_1dhyd  |  (-1)^d/(2d+1)
  s           | Sum the results
*4            | Print sum * 4

```
> 0 votes

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

```
S\n2@N{hax4

```

Try it online!

I spent so long golfing this just to beat Husk. No `hax` used.

```
S\n2@N{hax4
        ax  # Range [1, n]
       h    # Double
      {     # Subtract 1
    @N      # Negate
  n2        # Every other element
 \        4 # 4 divided by the list
S           # Sum

```
> 0 votes

# Answer
**ABAP**

```
    SELECTION-SCREEN BEGIN OF BLOCK b0.
    PARAMETERS: p_in TYPE i OBLIGATORY.
    SELECTION-SCREEN END OF BLOCK b0.

    START-OF-SELECTION.

    DATA: v_result      TYPE float.
    PERFORM calculate USING p_in CHANGING v_result.
    WRITE / v_result.

    FORM calculate USING v_in TYPE i
                   CHANGING v_result TYPE float.

      DATA: v_exponent,
            v_denominator,
            v_next  TYPE i.

      IF v_in = 1.
        v_result = v_result + 4.
        RETURN.
      ELSE.
        v_exponent = v_in + 1.
        v_denominator = ( 2 * v_in ) - 1.
        v_result = v_result + ( 4 * ( -1 ** v_exponent ) ) / v_denominator.
        v_next = v_in - 1.
        PERFORM calculate USING v_next CHANGING v_result.
      ENDIF.

```

ENDFORM.
> 0 votes

# Answer
# PowerShell Core, 42 bytes

```
1.."$args"|%{$s+=(-4,4)[$_%2]/(2*$_-1)}
$s

```

Try it online!
> 0 votes

# Answer
# Alice, 44 bytes

```
/
 M /e!]4aaE*R!0~w~?R.![?2+.!]:+~t.$K;\ O @

```

Try it online!

`Alice` does not support decimal, so instead of doing decimal, I'll output an integer, starting from `4e10`:

```
1 - 40000000000
2 - 26666666666
3 - 34666666666
4 - 28952380951

```

Please let me know if not OK and I'll withdraw the answer.

### Explanation

```
/M/4aaE*R!]e![0~w~?R.!]?2+.![:+~t.$K;\O@   Flattened
/M/                                        Reads an argument and pushes it into the stack
   4aaE*R!]e![                             Write two entries `-40000000000` and `-1` in the tape
              0                            Pushes 0 on the stack, we will sum the other terms of the series onto it
               ~w~             ~t.$K       Loops until we have repeated the loop `argument` times
                  ?R.!]?2+.![              From the tape, negate the first argument and add `2` to the second and update the tape with their new values
                             :+            Divide them (forms the nth term of the series) and add it to the series' sum
                                    ;\O@   Outputs the result and finishes

```
> 0 votes

# Answer
# jq, 32 bytes

```
[1+range(.*2)|drem(.;2)*4/.]|add

```

Attempt This Online!
> 0 votes

# Answer
# k, 17 bytes

```
+/(n#4 -4)%1+2*!n

```

`1+2*!n` generate the denominators

`n#4 -4` generate the numerators

`%` vector division

`+/` sum
> 0 votes

# Answer
# PARI/GP 32 bytes

```
p(n)=sum(k=s=1,n,4/(1-2*k)*s=-s)

```
> 0 votes

# Answer
# Thunno 2 `S`, 10 bytes

```
ıḌ⁻4\n⁺u@×

```

Try it online!

#### Explanation

```
ıḌ⁻4\n⁺u@×  # Implicit input
ı           # Map over [1..n]:
   4\       #  4 divided by...
 Ḍ⁻         #  (2 * n - 1)
         ×  #  Multiplied by
       u@   #  -1 to the power of...
     n⁺     #  (n + 1)
            # Implicit output of sum

```
> 0 votes

---
Tags: code-golf, sequence, pi
---


title: Advance Happy New Year, 2016!

text:
# Question
Title: Advance Happy New Year, 2016!
Your input will be a integer between 1970 and 2090 (inclusive), representing a year. Your program should output the next year on which New Years Day falls on the same day of the week as the input year.

**Test Cases:**

Below are the sample inputs and outputs

```
2001 => 2007
2047 => 2058
2014 => 2020
1970 => 1976
1971 => 1982
1977 => 1983
2006 => 2012

```

**20% Bonus:** Output the day of the week of New Years Day

```
2001 => 2007 (Mon)
2047 => 2058 (Tue)
2014 => 2020 (Wed)
1970 => 1976 (Thu)
1971 => 1982 (Fri)
1977 => 1983 (Sat)
2006 => 2012 (Sun)

```

**30% Bonus:** Output `Advance Happy New Year, <year>`

```
2010 => Advance Happy New Year, 2016

```

**50% Bonus:** Do both above bonuses

```
2010 => Advance Happy New Year, 2016 (Fri)

```

Write a program which reads input from STDIN or accepts command line arguments, or a function which takes an argument.

**Note:** Please add a link to test your code if possible.

**Leaderboard:**

```
    var QUESTION_ID=66656,OVERRIDE_USER=16196;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/66656/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://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}#answer-list{padding-right: 100px}
```

```
    <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
> 2 votes
## Jelly, 9 bytes

```
%4*3%7+5+

```

This is a monadic chain that takes an integer command-line argument as input. It uses my `(x+5+(x%4)**3%7)` algorithm.

Try it here. Although that's the current version of Jelly, it also works in this version, which predates the challenge. (Thanks @Dennis!)

# Answer
> 31 votes
## Mathematica, ~~45~~ ~~37~~ ~~27~~ 24 bytes

```
#+5[6,6,11][[#~Mod~4]]&

```

Improvements thanks to @MartinBüttner (10 bytes), and @ChipHurst (a further 3 bytes).

# Answer
> 18 votes
# CJam, ~~21~~ ~~12~~ 11 bytes

```
{_9587Cb=+}

```

@martin found a very simple method!

Try it here.

EDIT: Thanks, Dennis!

# Answer
> 10 votes
# gs2, 12 bytes

```
V@¶4☻s%☺♀i50

```

Translation of my CJam answer. Encoded in CP437 as usual. Try it online!

# Answer
> 8 votes
# JavaScript (ES6), ~~50~~ ~~49~~ 20 bytes (no bonuses)

```
a=>a+[5,6,6,11][a%4]

```

The algorithm by @martin proves to be much smaller, so I went with it.

I chose a mathematical approach because JavaScript tends to be verbose. The code is short enough that bonuses only make it longer.

Here is my previous answer (49 bytes), and my original answer (50 bytes):

`F=(a,b=a)=>((a+--a/4|0)-(b++/4+b|0))%7?F(++a,b):b`

`F=(a,b=a)=>(f=c=>(c--+c/4|0)%7)(a)-f(++b)?F(a,b):b`

They work by taking the year and calculating a number (0-6) to represent the "starting day of year". Because the date range for this challenge is within the range of years that follow simple leap year rules (no skipping on 2000), it's fairly straightforward to calculate. Then it's just a matter of comparing forward to find years that start with the same value. Recursion proved to be the most concise way to do this.

# Answer
> 7 votes
# Pyth, ~~14~~ ~~12~~ 11 bytes

```
+QC@"♣♠♠♂"Q

```

The four bytes in the string should be `05 06 06 0B`.

EDIT: Thanks, FryAmTheEggman!

EDIT: Thanks, Dennis!

# Answer
> 6 votes
# JavaScript (ES6), 104 bytes - 50% bonus = 52

```
y=>eval('for(a=0;a!=(b=(new Date(""+y++)+"").slice(0,3));a=a||b)`Advance Happy New Year, ${y} (`')+b+")"

```

## Explanation

```
y=>
  eval(`                  // eval enables for loop without {} or return
    for(
      a=0;                // a = first day of input year
      a!=                 // check if the day of the current year is equal to the first
        (b=(new Date(     // b = day of current year
          ""+y++)+"")     // cast everything as strings!
            .slice(0,3)); // the first 3 letters of the date string are the day name
      a=a||b              // set a to the day on the first iteration
    )

      // return the string
      \`Advance Happy New Year, \${y} (\`
  `)+b+")"

```

## Test

```
var solution = y=>eval('for(a=0;a!=(b=(new Date(""+y++)+"").slice(0,3));a=a||b)`Advance Happy New Year, ${y} (`')+b+")"
```

```
<input type="text" id="input" value="2001" />
<button onclick="result.textContent=solution(+input.value)">Go</button>
<pre id="result"></pre>
```

# Answer
> 6 votes
# Z80 machine code, 12 bytes

A Z80 procedure to be stored at `0000h`, called with the input in `HL`, and all other registers clear:

```
.org 0000h
              ; Bytes   ; Explanation
  ;---------------------------------------------------------------
  DEC B       ; 05      ;
  LD B, 6     ; 06 06   ;
  DEC BC      ; 0B      ;
  LD A, 3     ; 3E 03   ;   A = 3
  AND L       ; A5      ;   A = input & 3
  LD E, A     ; 5F      ;   A = input & 3     DE = input & 3
  LD A, (DE)  ; 1A      ;   A = [input & 3]   DE = input & 3
  LD E, A     ; 5F      ;   A = [input & 3]   DE = [input & 3]
  ADD HL, DE  ; 19      ;   HL = input + offset
  RET         ; C9      ;

```

The first three instructions are "NOPs", but are indexed as data later in the code. Upon returning, the output is in `HL`.

# Answer
> 5 votes
# Python 3, ~~140~~ ~~100~~ ~~102~~ ~~84.5~~ 154 * 0.5 = 77 bytes

~~I could probably write a better solution with Sakamoto's algorithm, but this will do for now~~

I was right. Here's an implementation using Sakamoto's algorithm.

```
def s(y):
 d=lambda j:(j+j//4)%7
 for i in range(y,y+15):
  if d(i)==d(y-1):return"Advance Happy New Year, %d (%s)"%(-~i,"SMTWTFSuouehranneduit"[d(i)::7])

```

Explanation:

```
def day_of_the_week(year):
    return (year + year//4 - 1 + 0 + 1) % 7
    # The month code for January is 0, and you add 1 from January *1*.
    # The -1 is to correct for starting on Saturday
    # and so that it cancels out the 1 from January 1.

def new_years(this_year):
# But in Sakamoto's algorithm, if the month is January or February, we must subtract 1.
    weekdays = "SunMonTueWedThuFriSat"
    for item in range(this_year, this_year + 15):
        if day_of_the_week(this_year - 1) == day_of_the_week(item):
            day = weekdays[day_of_the_week(item)*3 : day_of_the_week(item)*3+3]
            return "Advance Happy New Year, %d (%s)"%(item + 1, day)
        # So we subtract from every year we check, including this_year
        # And add 1 back in at the end
        # And print the greeting, the year, and the corresponding day of the week

```

# Answer
> 4 votes
## Seriously, ~~35~~ 17 bytes

`[5,6,6,11]` trick saves the day.

```
4,;)%[5,6,6,11]E+

```

Try it online

Explanation:

```
4,;)%[5,6,6,11]E+
4,;)%              push input, input % 4
     [5,6,6,11]E   push (input % 4)th element of [5,6,6,11]
                +  add to the input

```

Old version:

```
,;;D`45/*≈7@%`;╝ƒ╗35*r+`╛ƒ╜=`M1@íu+

```

Try it online

Explanation:

```
,;;D`45/*≈7@%`;╝ƒ╗35*r+`╛ƒ╜=`M1@íu+
,;;                                  push 3 copies of the input (n)
   D                                 decrement the top copy of n
    `45/*≈7@%`;╝                     push Sakamoto's algorithm as a function and save a copy in register 1
                ƒ╗                   call Sakamoto's algorithm function and save result in register 0
                  35*r+              push [n, n+1, ..., n+14]
                       `    `M       map the function:
                        ╛ƒ╜=           push Sakamoto's algorithm, call, push 1 if equal to value in register 0 else 0
                              1@í    get the index of the first 1
                                 u+  increment and add n

```

Sakamoto's algorithm:

```
45/*≈7@%
45/*      multiply by 5/4
    ≈     floor
     7@%  mod 7

```

# Answer
> 4 votes
# C, 31 bytes

Following the edit to the question that restricts the input range to 1970-2090, this becomes pretty trivial:

```
f(x){return"\5\6\6\13"[x%4]+x;}

```

Without the non-leap century years, there's a simple 5,6,6,11 sequence of intervals for the first repeat of the same day.

Complete solution to original problem (not constrained to 2090), 90 bytes:

```
f(x){return(x-1)%100>89&&(x+9)/100%4?"\6\14\5\6\6\6\6\7\14\6"[x%10]+x:"\5\6\6\13"[x%4]+x;}

```

### Test program:

```
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    while (*++argv)
        printf("Advance Happy New Year, %d\n", f(atoi(*argv)));
    return !argc;
}

```

# Test run:

```
$ ./66656 2001 2047 2014 1970 1971 1977 2006
Advance Happy New Year, 2007
Advance Happy New Year, 2058
Advance Happy New Year, 2020
Advance Happy New Year, 1976
Advance Happy New Year, 1982
Advance Happy New Year, 1983
Advance Happy New Year, 2012

```

# Answer
> 4 votes
## R, ~~143~~ 136 * 0.5 = 68 bytes

```
G=function(y)strftime(paste(y,1,1,sep='-'),'%a')
d=seq(y<-scan(),y+14);sprintf("Advance Happy New Year, %i (%s)",d[G(d)==(w=G(y))][2],w)

```

Use `%A` for full day name instead of \`%a, depend on desired state.

## R, 120 * 0.7 = 84 bytes

```
G=function(y)as.POSIXlt(paste(y,1),,"%Y %j")$wday
d=seq(y<-scan(),y+14);cat("Advance Happy New Year,",d[G(d)==G(y)][2])

```

## R, 90 bytes

```
G=function(y)as.POSIXlt(paste(y,1),,"%Y %j")$wday
d=seq(y<-scan(),y+14);d[G(d)==G(y)][2]

```

---

All answers above are derivative work based on @plannapus answer. Using the `;` separator to avoid needing to `source` the file or run it as script on command line.

# Answer
> 3 votes
# R, 145 bytes -50% -\> 72.5

```
y=scan();F=function(y)format(as.POSIXct(paste(y,1),,"%Y %j"),"%a");x=y+1;while(F(x)!=F(y))x=x+1;sprintf("Advance Happy New Year, %i (%s)",x,F(x))

```

Examples:

```
> y=scan();F=function(y)format(as.POSIXct(paste(y,1),,"%Y %j"),"%a");x=y+1;while(F(x)!=F(y))x=x+1;sprintf("Advance Happy New Year, %i (%s)",x,F(x))
1: 2006
2:
Read 1 item
[1] "Advance Happy New Year, 2012 (Sun)"
> y=scan();F=function(y)format(as.POSIXct(paste(y,1),,"%Y %j"),"%a");x=y+1;while(F(x)!=F(y))x=x+1;sprintf("Advance Happy New Year, %i (%s)",x,F(x))
1: 1977
2:
Read 1 item
[1] "Advance Happy New Year, 1983 (Sat)"
> y=scan();F=function(y)format(as.POSIXct(paste(y,1),,"%Y %j"),"%a");x=y+1;while(F(x)!=F(y))x=x+1;sprintf("Advance Happy New Year, %i (%s)",x,F(x))
1: 2014
2:
Read 1 item
[1] "Advance Happy New Year, 2020 (Wed)"

```

## R, 97 bytes (without bonus)

```
y=scan();F=function(y)format(as.POSIXct(paste(y,1),,"%Y %j"),"%w");x=y+1;while(F(x)!=F(y))x=x+1;x

```

Indented, with new lines:

```
y = scan() #Takes input from stdin
F = function(y)format(as.POSIXct(paste(y,1),,"%Y %j"),"%w") #Year to Weekday
x = y+1
while(F(x) != F(y)) x = x+1
x

```

Test cases:

```
> y=scan();F=function(y)format(as.POSIXct(paste(y,1),,"%Y %j"),"%w");x=y+1;while(F(x)!=F(y))x=x+1;x
1: 1977
2:
Read 1 item
[1] 1983
> y=scan();F=function(y)format(as.POSIXct(paste(y,1),,"%Y %j"),"%w");x=y+1;while(F(x)!=F(y))x=x+1;x
1: 2006
2:
Read 1 item
[1] 2012
> y=scan();F=function(y)format(as.POSIXct(paste(y,1),,"%Y %j"),"%w");x=y+1;while(F(x)!=F(y))x=x+1;x
1: 2016
2:
Read 1 item
[1] 2021

```

# Answer
> 3 votes
# PHP, 120 ~~139~~ bytes - 50% = 60 bytes

A functional approach:

```
$s=strtotime;for($d=date(D,$s(($y=$argv[1]).$_="-1-1"));$d!=date(D,$s(++$y.$_)););echo"Advance Happy New Year, $y ($d)";

```

Takes one input from command line, like:

```
$ php ahny.php 2001

```

**The OOP way seems to be longer, as always (143 bytes):**

```
$s=strtotime;for($d=date(D,$s($x=($y=$argv[1])."-1-1"));$d!=date(D,$s(++$y."-1-1")););echo"Advance Happy New Year, $y ($d)";

```

**Edits**

* *Saved* **18 bytes**. Instead of adding one year using the PHP modifier `+1year`, I now simply increment the given year.
* *Saved* **1 byte** by storing `-1-1` in a variable.

# Answer
> 3 votes
# VBA, 130 * 0.50 = 65 Bytes

```
Sub k(y)
i=1
Do While Weekday(y+i)<>Weekday(y)
i=i+1
Loop
MsgBox "Advance Happy New Year," &y+i &WeekdayName(Weekday(y+i))
End Sub

```

VBA makes finding week days so easy.... If only it wasn't so Verbose about it.

# Answer
> 3 votes
# C, score ~~53~~ 52 (104 bytes)

```
f(x){x+="0116"[x%4];printf("Advance Happy New Year, %d (%.3s)",x-43,"MonTueWedThuFriSatSun"+x*5/4%7*3);}

```

Idea borrowed from Toby Speight; added the bonus display of weekday.

Shortened the string by shifting the character codes to a more comfortable range. Had to choose the right shifting amount (e.g. 43) to make the short weekday calculation code `x*5/4%7` work.

# Answer
> 2 votes
# Java, ~~(1-.2)\*323~~ (1-.5)\*~~350~~ ~~348~~ 339 = ~~258.4~~ ~~175~~ ~~174~~ 169.5 bytes

```
import java.text.*;class D{public static void main(String[]a){long y=new Long(a[0]);int i=0;for(;!s(y).equals(s(y+(++i))););System.out.printf("Advance Happy New Year, %d (%s)",y+i,s(y+i));}static String s(long y){try{return new SimpleDateFormat("E").format(new SimpleDateFormat("d/M/yyyy").parse("1/1/"+y));}catch(Exception e){}return"";}}
```

Ugh.

Ungolfed:

```
import java.text.*;
class D{
    public static void main(String[]a){
        long y=new Long(a[0]);
        int i=0;
        for(;!s(y).equals(s(y+(++i))););
        System.out.printf("Advance Happy New Year, %i (%s)",y+i,s(y+i));
    }
    static String s(long y){
        try{
            return new SimpleDateFormat("E").format(new SimpleDateFormat("d/M/yyyy").parse("1/1/"+y));
        }catch(Exception e){}
        return"";
    }
}
```

Try it online!

Thanks to @Kenney for pointing out that I could shorten with `new Long` and `printf`! :D

# Answer
> 2 votes
# GNU coreutils, 52 51 49 bytes

(98 bytes program - 50% bonus)

```
seq -f$1-1-1\ %gyear 28|date -f- +'Advance Happy New Year, %Y (%a)'|sed /`date -d$1-1-1 +%a`/!d\;q

```

Input is from command-line argument, and output is to stdout.

### Explanation

```
# generate 28 input years from $1 + 1 onwards (28 is always enough)
seq -f '$1-1-1 %g year' 28
|
# convert all of these as potential outputs
date -f- +'Advance Happy New Year, %Y (%a)'
|
 # Select the first one where the dayname matches that of input year
sed "/`date -d$1-1-1 +%a`/!d;q"

```

### Test run:

All locale settings can be `C` or `POSIX`.

```
$ for i in 2001 2047 2014 1970 1971 1977 2006; do ./66656.sh $i; done
Advance Happy New Year, 2007 (Mon)
Advance Happy New Year, 2058 (Tue)
Advance Happy New Year, 2020 (Wed)
Advance Happy New Year, 1976 (Thu)
Advance Happy New Year, 1982 (Fri)
Advance Happy New Year, 1983 (Sat)
Advance Happy New Year, 2012 (Sun)

```

Limitation: this only works up to year 2147485519 (though the question is now changed to permit a lower limit).

# Answer
> 2 votes
## Mathematica, 145 * 50% = ~~74~~ ~~73.5~~ 72.5 bytes

```
d=DateValue;StringForm["Advance Happy New Year, `` (``)",NestWhile[#+1&,(a=#)+1,#!=#2&@@DateObject@{{a},{#}}~d~"DayName"&],{a}~d~"DayNameShort"]&

```

Uses standard date functions.

# Answer
> 2 votes
## Pyth, 23 bytes

```
L%+/b4b7.VQIqyby-Q1+1bB

```

Doesn't qualify for any of the bonuses.

Try it here.

Similar to the pure python answer.

```
                        - Q = eval(input()) (autoassigned)
L                       - y = lambda b:
   /b4                  - b floordiv 4
  +   b                 - + b
 %     7                - mod 7

        .VQ             - for b in range(Q, infinate):
           Iqyby-Q1     - if y(b) == y(Q-1):
                   +1b  - print b+1
                      B - break

```

# Answer
> 2 votes
# MATL, 28 bytes

```
i0:14+t1tI$YO8H$XO!st1)=f2))

```

### Example

```
>> matl i0:14+t1tI$YO8H$XO!st1)=f2))
> 1970
1976

```

### Code explained

```
i           % input year
0:14+       % vector with that year and the next 14
t1tI$YO     % first day of each year
8H$XO       % transform into three letters specifying weekday
!s          % sum those three letters to reduce to unique numbers
t1)         % get first of those numbers (corresponding to input year)
=f2)        % find index of second matching
)           % index with that to obtain output year

```

# Answer
> 2 votes
# Perl 6,  ~~70~~  23 bytes

~~```
{($^a+1...{[==] ($a,$_).map: {Date.new(:year($_)).day-of-week}})[*-1]} # 70 bytes

```~~
```
{($_ X+5,6,6,11)[$_%4]} # 23 bytes

```

usage:

```
for «2001 2047 2014 1970 1971 1977 2006 2010» {
  printf "%d => %d\n", $_, {($_ X+5,6,6,11)[$_%4]}( $_ )
}

```

```
2001 => 2007
2047 => 2058
2014 => 2020
1970 => 1976
1971 => 1982
1977 => 1983
2006 => 2012
2010 => 2016

```

# Answer
> 2 votes
# Jelly, 14 bytes

```
%4=0,3×-,5S++6

```

Try it online!

Until today, Jelly had no array indexing, so the above will have to do. Since the latest commit, array indexing has been implemented as , giving the following solution (**10 bytes**).

```
ị6,6,11,5+

```

Try it online!

# Answer
> 2 votes
# J, 14 bytes

```
+5 6 6 11{~4&|

```

# Answer
> 2 votes
# Japt, 12 bytes

```
U+"♣♠♠♂"cU%4

```

As with the Pyth answer, the four bytes in the string should be `05 06 06 0B`. Try it online!

```
U+"♣♠♠♂"cU%4  // Implicit: U = input integer
  "♣♠♠♂"      // Take this string.
        cU%4  // Take the char code at U%4.
U+            // Add U.
              // Implicit: output last expression

```

# Answer
> 2 votes
# Pyth, 35 bytes

```
Iq%Q4 3=+Q11).?Iq%Q4 0=+Q5).?=+Q6;Q

```

Try it online.

# Answer
> 1 votes
# C# (6.0) .Net Framework 4.6 173 Bytes - 30% = 121.1 Bytes

```
void n(int y)=>Console.Write($"Advance Happy New Year, {Enumerable.Range(1,15).Select(i=>new DateTime(y+i,1,1)).First(x=>x.DayOfWeek==new DateTime(y,1,1).DayOfWeek).Year}");

```

# Answer
> 1 votes
## Javascript ES7, 17 bytes

```
a=>a+5+(a%4)**3%7

```

It's my first time using JS. I found this using a Python script, and I believe it to be optimal. It works because `0**3` is 0 mod 7, `1**3` and `2**3` are both 1, and `3**3` is 6.

# Answer
> 1 votes
## Python, 23 bytes

```
lambda a:a+5+(a%4)**3%7

```

A port of my JavaScript answer.

# Answer
> 1 votes
# Pyth, 12 bytes

```
++5%^%Q4 3 7

```

**Try it online!** or **Check out the Test Suite.**

# Pyth, 18 bytes

This second approach is mainly a golf of @wizzwizz4's Pyth answer.

```
J%Q4+?q3J11?qJZ5 6

```

**Try it online!** or **Check out the Test Suite.**

---

# Explanation

```
++5%^%Q4 3 7Q  - Q means evaluated input and is implicit at the end.

     %Q4       - Input mod 4.
    ^    3     - Cubed.
   %       7   - Mod 7.
 +5            - Plus 5
+           Q  - Plus the input.

```

# Answer
> 1 votes
# Thunno 2, 8 bytes

```
4%³7%+5+

```

Try it online!

Port of lirtosiast's Jelly answer.

#### Explanation

```
4%³7%+5+  # Implicit input
4%        # Input mod 4
  ³       # Cubed
   7%     # Mod 7
     +5+  # Plus 5 plus input
          # Implicit output

```

Old:

```
4%¿çƑ{ç¿i+  # Implicit input
4%          # Input mod 4
        i   # Indexed into
  ¿çƑ{ç¿    # The list [5,6,6,11]
         +  # Added to the input
            # Implicit output

```

# Answer
> 1 votes
# Vyxal, 9 bytes

```
4%3e7%+5+

```

Try it Online!

Port of lirtosiast's Jelly answer.

*-2 thanks to @lyxal*

#### Explanation

```
4%3e7%+5+  # Implicit input
4%         # Input mod 4
  3e       # Cubed
    7%     # Mod 7
      +5+  # Plus 5 plus input
           # Implicit output

```

Old:

```
4%»&ṗ»12τi+  # Implicit input
4%           # Input mod 4
         i   # Indexed into
  »&ṗ»12τ    # The list [5,6,6,11]
          +  # Added to the input
             # Implicit output

```

# Answer
> 0 votes
# Python 2, 32 bytes

```
x=input()
print[5,6,6,11][x%4]+x

```

Uses the `5 6 6 11` trick.

# Answer
> 0 votes
# 2, 12 chars / 18 bytes (non-competitive)

```
ï+⟨566ḋ[ï%4]

```

`Try it here (Firefox only).`

# Explanation

```
ï+⟨566ḋ[ï%4] // implicit: ï = input, ḋ = 11
ï+           // add ï to:
  ⟨566ḋ      // [5,6,6,11]
       [ï%4] // get index at input mod 4

```

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