# Question
Title: Pointlessly make your way down the alphabet
*Disclaimer:* This challenge inspired by me spending the morning debugging recursive functions, which have been frying my brain a little.

Here's an example of recursion, from a letter, we keep going to the previous letter of the alphabet, printing out each one as we go, until we hit the letter a, then we print that and stop. We do this for each letter in a string and there's a pretty pattern at the end of it.

# The task

* Start with a string of characters
    + The input string may only contain the lower-case letters a-z and the space character.
* For each letter, produce a line of text (terminal output or variable or whatever)
    + Print out the letter
    + Print out the previous letter (on the same line)
    + Print out the previous letter (on the same line)
    + Print out the previous letter (on the same line)
    + ...
    + If the letter is 'a', print it out and move to the next line.
    + If it's a space, print out an empty line (or one just containing the space character.

# The rules

* It's golf, try and make your code short.
* Any language you like.
* Please include a link to an online interpreter.
* The output should be human-readable (e.g. I can't work it out from a list of bytes.
* Follow the rules of the standard loopholes `¯\_(ツ)_/¯`
* Recursion is not mandated by the rules, but it's probably necessary.

# Test Cases

Input: 'abcdefghijklmnopqrstuvwxyz' Output:

```
a
ba
cba
dcba
edcba
fedcba
gfedcba
hgfedcba
ihgfedcba
jihgfedcba
kjihgfedcba
lkjihgfedcba
mlkjihgfedcba
nmlkjihgfedcba
onmlkjihgfedcba
ponmlkjihgfedcba
qponmlkjihgfedcba
rqponmlkjihgfedcba
srqponmlkjihgfedcba
tsrqponmlkjihgfedcba
utsrqponmlkjihgfedcba
vutsrqponmlkjihgfedcba
wvutsrqponmlkjihgfedcba
xwvutsrqponmlkjihgfedcba
yxwvutsrqponmlkjihgfedcba
zyxwvutsrqponmlkjihgfedcba

```

Input: 'zyxwvutsrqponmlkjihgfedcba'

```
zyxwvutsrqponmlkjihgfedcba
yxwvutsrqponmlkjihgfedcba
xwvutsrqponmlkjihgfedcba
wvutsrqponmlkjihgfedcba
vutsrqponmlkjihgfedcba
utsrqponmlkjihgfedcba
tsrqponmlkjihgfedcba
srqponmlkjihgfedcba
rqponmlkjihgfedcba
qponmlkjihgfedcba
ponmlkjihgfedcba
onmlkjihgfedcba
nmlkjihgfedcba
mlkjihgfedcba
lkjihgfedcba
kjihgfedcba
jihgfedcba
ihgfedcba
hgfedcba
gfedcba
fedcba
edcba
dcba
cba
ba
a

```

Input: 'hello world' Output:

```
hgfedcba
edcba
lkjihgfedcba
lkjihgfedcba
onmlkjihgfedcba

wvutsrqponmlkjihgfedcba
onmlkjihgfedcba
rqponmlkjihgfedcba
lkjihgfedcba
dcba

```

# Answer
# Dyalog APL Extended, 4 bytes

```
⌽∘⍳¨

```

Try it online!

```
 ∘    the function composition of
  ⍳     iota - 'a'..input for alphabet chars, empty array for space
⌽       and after, reverse
   ¨  applied to each

```
> 33 votes

# Answer
# C (gcc),  ~~58~~  56 bytes

*Saved 2 bytes thanks to @KritixiLithos*

```
c;f(char*s){while(c=c&&putchar(c>96?c:10)^10?c-1:*s++);}

```

Try it online!
> 14 votes

# Answer
# Haskell, ~~26~~ 24 bytes

*-2 bytes thanks to FrownyFrog.*

```
map(\i->reverse['a'..i])

```

Try it online!

Pointless (or pointfree :P) for you.
> 14 votes

# Answer
# Malbolge20 and Malbolge Unshackled polyglot, around 2MB, 107KB compressed.

Alright. I spent around 30 minutes on this answer (current record). It's really optimal answer. Albeit not so fast and not so memory-exhausting (only ~512 megabytes), it's still a Malbolge answer so please keep that noted.

The program is packed using 7zip and PPMd compression algorithm. You can download it here.

## Interpreter that works the best with the program.

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

const char* translation = "5z]&gqtyfr$(we4{WP)H-Zn,[%\\3dL+Q;>U!pJS72Fh"
        "OA1CB6v^=I_0/8|jsb9m<.TVac`uY*MK'X~xDl}REokN:#?G\"i@";

typedef struct Word {
    unsigned int area;
    unsigned int high;
    unsigned int low;
} Word;

void word2string(Word w, char* s, int min_length) {
    if (!s) return;
    if (min_length < 1) min_length = 1;
    if (min_length > 20) min_length = 20;
    s[0] = (w.area%3) + '0';
    s[1] = 't';
    char tmp[20];
    int i;
    for (i=0;i<10;i++) {
        tmp[19-i] = (w.low % 3) + '0';
        w.low /= 3;
    }
    for (i=0;i<10;i++) {
        tmp[9-i] = (w.high % 3) + '0';
        w.high /= 3;
    }
    i = 0;
    while (tmp[i] == s[0] && i < 20 - min_length) i++;
    int j = 2;
    while (i < 20) {
        s[j] = tmp[i];
        i++;
        j++;
    }
    s[j] = 0;
}

unsigned int crazy_low(unsigned int a, unsigned int d){
    unsigned int crz[] = {1,0,0,1,0,2,2,2,1};
    int position = 0;
    unsigned int output = 0;
    while (position < 10){
        unsigned int i = a%3;
        unsigned int j = d%3;
        unsigned int out = crz[i+3*j];
        unsigned int multiple = 1;
        int k;
        for (k=0;k<position;k++)
            multiple *= 3;
        output += multiple*out;
        a /= 3;
        d /= 3;
        position++;
    }
    return output;
}

Word zero() {
    Word result = {0, 0, 0};
    return result;
}

Word increment(Word d) {
    d.low++;
    if (d.low >= 59049) {
        d.low = 0;
        d.high++;
        if (d.high >= 59049) {
            fprintf(stderr,"error: overflow\n");
            exit(1);
        }
    }
    return d;
}

Word decrement(Word d) {
    if (d.low == 0) {
        d.low = 59048;
        d.high--;
    }else{
        d.low--;
    }
    return d;
}

Word crazy(Word a, Word d){
    Word output;
    unsigned int crz[] = {1,0,0,1,0,2,2,2,1};
    output.area = crz[a.area+3*d.area];
    output.high = crazy_low(a.high, d.high);
    output.low = crazy_low(a.low, d.low);
    return output;
}

Word rotate_r(Word d){
    unsigned int carry_h = d.high%3;
    unsigned int carry_l = d.low%3;
    d.high = 19683 * carry_l + d.high / 3;
    d.low = 19683 * carry_h + d.low / 3;
    return d;
}

// last_initialized: if set, use to fill newly generated memory with preinitial values...
Word* ptr_to(Word** mem[], Word d, unsigned int last_initialized) {
    if ((mem[d.area])[d.high]) {
        return &(((mem[d.area])[d.high])[d.low]);
    }
    (mem[d.area])[d.high] = (Word*)malloc(59049 * sizeof(Word));
    if (!(mem[d.area])[d.high]) {
        fprintf(stderr,"error: out of memory.\n");
        exit(1);
    }
    if (last_initialized) {
        Word repitition[6];
        repitition[(last_initialized-1) % 6] =
                ((mem[0])[(last_initialized-1) / 59049])
                    [(last_initialized-1) % 59049];
        repitition[(last_initialized) % 6] =
                ((mem[0])[last_initialized / 59049])
                    [last_initialized % 59049];
        unsigned int i;
        for (i=0;i<6;i++) {
            repitition[(last_initialized+1+i) % 6] =
                    crazy(repitition[(last_initialized+i) % 6],
                        repitition[(last_initialized-1+i) % 6]);
        }
        unsigned int offset = (59049*d.high) % 6;
        i = 0;
        while (1){
            ((mem[d.area])[d.high])[i] = repitition[(i+offset)%6];
            if (i == 59048) {
                break;
            }
            i++;
        }
    }
    return &(((mem[d.area])[d.high])[d.low]);
}

unsigned int get_instruction(Word** mem[], Word c,
        unsigned int last_initialized,
        int ignore_invalid) {
    Word* instr = ptr_to(mem, c, last_initialized);
    unsigned int instruction = instr->low;
    instruction = (instruction+c.low + 59049 * c.high
            + (c.area==1?52:(c.area==2?10:0)))%94;
    return instruction;
}

int main(int argc, char* argv[]) {
    Word** memory[3];
    int i,j;
    for (i=0; i<3; i++) {
        memory[i] = (Word**)malloc(59049 * sizeof(Word*));
        if (!memory) {
            fprintf(stderr,"not enough memory.\n");
            return 1;
        }
        for (j=0; j<59049; j++) {
            (memory[i])[j] = 0;
        }
    }
    Word a, c, d;
    unsigned int result;
    FILE* file;
    if (argc < 2) {
        // read program code from STDIN
        file = stdin;
    }else{
        file = fopen(argv[1],"rb");
    }
    if (file == NULL) {
        fprintf(stderr, "File not found: %s\n",argv[1]);
        return 1;
    }
    a = zero();
    c = zero();
    d = zero();
    result = 0;
    while (!feof(file)){
        unsigned int instr;
        Word* cell = ptr_to(memory, d, 0);
        (*cell) = zero();
        result = fread(&cell->low,1,1,file);
        if (result > 1)
            return 1;
        if (result == 0 || cell->low == 0x1a || cell->low == 0x04)
            break;
        instr = (cell->low + d.low + 59049*d.high)%94;
        if (cell->low == ' ' || cell->low == '\t' || cell->low == '\r'
                || cell->low == '\n');
        else if (cell->low >= 33 && cell->low < 127 &&
                (instr == 4 || instr == 5 || instr == 23 || instr == 39
                    || instr == 40 || instr == 62 || instr == 68
                    || instr == 81)) {
            d = increment(d);
        }
    }
    if (file != stdin) {
        fclose(file);
    }
    unsigned int last_initialized = 0;
    while (1){
        *ptr_to(memory, d, 0) = crazy(*ptr_to(memory, decrement(d), 0),
                *ptr_to(memory, decrement(decrement(d)), 0));
        last_initialized = d.low + 59049*d.high;
        if (d.low == 59048) {
            break;
        }
        d = increment(d);
    }
    d = zero();

    unsigned int step = 0;
    while (1) {
        unsigned int instruction = get_instruction(memory, c,
                last_initialized, 0);
        step++;
        switch (instruction){
            case 4:
                c = *ptr_to(memory,d,last_initialized);
                break;
            case 5:
                if (!a.area) {
                    printf("%c",(char)(a.low + 59049*a.high));
                }else if (a.area == 2 && a.low == 59047
                        && a.high == 59048) {
                    printf("\n");
                }
                break;
            case 23:
                a = zero();
                a.low = getchar();
                if (a.low == EOF) {
                    a.low = 59048;
                    a.high = 59048;
                    a.area = 2;
                }else if (a.low == '\n'){
                    a.low = 59047;
                    a.high = 59048;
                    a.area = 2;
                }
                break;
            case 39:
                a = (*ptr_to(memory,d,last_initialized)
                        = rotate_r(*ptr_to(memory,d,last_initialized)));
                break;
            case 40:
                d = *ptr_to(memory,d,last_initialized);
                break;
            case 62:
                a = (*ptr_to(memory,d,last_initialized)
                        = crazy(a, *ptr_to(memory,d,last_initialized)));
                break;
            case 81:
                return 0;
            case 68:
            default:
                break;
        }

        Word* mem_c = ptr_to(memory, c, last_initialized);
        mem_c->low = translation[mem_c->low - 33];

        c = increment(c);
        d = increment(d);
    }
    return 0;
}

```

## It works!
> 14 votes

# Answer
# PowerShell, ~~37~~ 28 bytes

<sup>-9 bytes thanks to mazzy</sup>

```
$args|%{-join($_..'a'-le$_)}

```

Try it online!

Takes input via splatting and uses char ranges introduced in PS v6. The range is then filtered out by only taking elements that are less than the current character. This in turns means decreasing ranges are unaffected (e.g. 'z'..'a') whereas increasing ranges (e.g. ' '..'a') will filter out everything except the space.
> 8 votes

# Answer
# Python 3, 65 bytes

```
lambda s:print([''.join(map(chr,range(ord(c),96,-1)))for c in s])

```

Outputs a list of strings as clarified in @Arnauld's comment.

If we could assume that a string `s` existed with the content it would be 56 bytes.

Try it online!
> 7 votes

# Answer
# Sed (with `-r` switch), ~~65~~ ~~61~~ ~~60~~ 59 characters

```
s/./&zyxwvutsrqponmlkjihgfedcba \n/g
s/(.).*\1/\1/gm
s/ //g

```

Thanks to:

* Kritixi Lithos for finding an unnecessary capturing (-3 characters)
* Kritixi Lithos for ~~anchoring to line start~~ not anchoring instead of word start (~~-1~~ 2 characters)
* Kritixi Lithos for combining the 2 solutions advantages (2 characters)

Sample run:

```
bash-5.0$ sed -r 's/./&zyxwvutsrqponmlkjihgfedcba \n/g;s/(.).*\1/\1/gm;s/ //g' <<< 'cg cc'
cba
gfedcba

cba
cba

```

Try it online!

### Sed (with `-r` switch), ~~53~~ 52 characters

```
s/./&zyxwvutsrqponmlkjihgfedcba \n/g
s/(.).*\1/\1/gm

```

In case trailing spaces are acceptable.

Try it online!
> 7 votes

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

Takes input as a list of characters. Returns a list of strings.

```
s=>s.map(g=c=>(c|=(B=Buffer)(c)[0])>96?B([c--])+g(c):'')

```

Try it online!

### Commented

```
s =>                 // s[] = input characters
  s.map(g = c =>     // for each character c in s[], using the recursive function g:
    ( c |=           //   update c:
        (B = Buffer) //     on the first iteration, c is a character and Buffer(c)[0]
        (c)[0]       //     returns its ASCII code; on later iterations, c is an
                     //     integer and Buffer(c) creates a buffer filled with NUL bytes
    ) > 96 ?         //     if c is greater than 96:
      B([c--])       //       append the character of ASCII code c and decrement c
      + g(c)         //       append the result of a recursive call
    :                //     else:
      ''             //       stop recursion
  )                  // end of map()

```
> 6 votes

# Answer
# , ~~63~~ ~~62~~ 61 bytes

-16 bytes thanks to Giuseppe

-7 more bytes, again, thanks to Giuseppe

-1 byte adding a line break in place of `\n`

-1 byte thanks to Robin Ryder

```
for(l in utf8ToInt(scan(,""))-96)cat(letters[l:0],'
',sep="")

```

Try it online!

# , 86 bytes (my original answer)

```
x=utf8ToInt(scan(,''));s=sapply;cat(gsub(" .+"," ",s(s(x,`:`,97),intToUtf8)),sep="\n")

```

Ungolfed:

```
x=utf8ToInt(scan(,''))                                 #Takes input, converts to ASCII
s=sapply;                                              #Alias sapply function to save a byte
                     s(x,`:`,97)                       #Create vector from 97 to respective ASCII value
                   s(           ,intToUtf8)            #Convert to character
    gsub(" .+"," ",                        )           #Removes everything after space
cat(                                        ,sep="\n") #Outputs to console

```

Try it online!

Could likely be golfed.

NOTE: It does not use recursion. I do not know whether that would be shorter or not. I'll experiment later.
> 6 votes

# Answer
# C (gcc), ~~56~~, 53 bytes

```
c;f(char*s){for(c=*s;c;)putchar(c<97?c=*++s,10:c--);}

```

Try it online!

Now down to 53 bytes! It can probably be golfed more though...
> 6 votes

# Answer
# 05AB1E, ~~14~~ ~~12~~ 5 bytes

```
AAηí‡

```

-2 bytes by outputting as a list of strings.
-7 bytes (byte-count more than halved) thanks to *@Grimy*.

Input as a list of characters.

Try it online or verify all test cases.

Or alternatively:

```
AÂ.s‡

```

Try it online or verify all test cases.

**Explanation:**

```
A      # Push the lowercase alphabet
 Aη    # Push a list of prefixes of the lowercase alphabet
   í   # Reverse each prefix
    ‡  # Transliterate all characters of the alphabet to these reversed prefixes in
       # the (implicit) input-list
       # (after which the resulting string-list is output implicitly)

A      # Push the lowercase alphabet
 Â     # Bifurcate it; short for Duplicate & Reverse copy
  .s   # Get the suffixes of that reversed alphabet
    ‡  # Transliterate all characters of the alphabet to these reversed suffixes in
       # the (implicit) input-list
       # (after which the resulting string-list is output implicitly)

```
> 5 votes

# Answer
# Perl 6, 24 bytes

```
*.comb>>.&{[R~] 'a'..$_}

```

Try it online!

Returns a list of strings.

### Explanation

```
*.comb  # Split into characters
      >>.&{            }  # Map to
                'a'..$_   # Range 'a' to current character
           [R~]           # Reverse concat

```
> 5 votes

# Answer
# Jelly,  ~~8~~  7 bytes

A monadic link returning a list of strings.

```
ḲOr97ỌK

```

Try it online!

```
ḲOr97ỌK   - a monadic link taking a string, e.g. "ab c"
Ḳ         - split at spaces                 --> ["ab", "c"]
 O        - get ASCII codes                 --> [[97, 98], [99]]
  r97     - build descending range to 97    --> [[[97], [98, 97]], [[99, 98, 97]]]
     Ọ    - turn back into ASCII            --> [["a", "ba"], ["cba"]]
      K   - join with spaces                --> ["a", "ba", " ", "cba"]

```
> 5 votes

# Answer
# K (oK), ~~17~~ 14 bytes

-3 bytes thanks to streetster

-3 bytes thanks to ngn

```
`c$96-!:'0&96-

```

Try it online!
> 5 votes

# Answer
# GolfScript, 12 bytes

```
{),97>-1%n}%

```

Try it online!

## Explanation

```
{         }% # Map over the implicit input
 ),          # Generate range to 0x00
   97>       # Remove all that is less than 97
      -1%    # Reverse the string
         n   # Add a newline

```
> 5 votes

# Answer
# Ruby, 41 characters

```
->s{s.chars{|c|puts [*?a..c].reverse*''}}

```

or

```
->s{s.gsub(/./){[*?a..$&].reverse*''+$/}}

```

No recursion here.

Sample run:

```
irb(main):001:0> ->s{s.chars{|c|puts [*?a..c].reverse*''}}['cgcc']
cba
gfedcba
cba
cba

```

Try it online!
> 4 votes

# Answer
# Wren, 103 bytes

Hopefully this beats the Lua answer.

```
Fn.new{|x|
for(i in x)System.print(i==" "?"":(i.bytes[0]..97).map{|j|String.fromCodePoint(j)}.join())
}

```

Try it online!

# Wren, 159 bytes

I am not having enough fun.

```
Fn.new{|x|
for(i in 122..97)x=x.replace(String.fromCodePoint(i),String.fromCodePoint(i)+String.fromCodePoint(i-1))
return x.replace("`","
").replace(" ","
")
}

```

Try it online!
> 4 votes

# Answer
# PostgreSQL, 119 characters

```
\prompt s
select(select string_agg(chr(s),'')from generate_series(ascii(c),97,-1)s)from regexp_split_to_table(:'s','')c

```

(Those verbose function names are killing me…)

Sample run:

```
bash-5.0$ psql -Atf pointlessly-recurse.sql <<< 'hello world'
hgfedcba
edcba
lkjihgfedcba
lkjihgfedcba
onmlkjihgfedcba

wvutsrqponmlkjihgfedcba
onmlkjihgfedcba
rqponmlkjihgfedcba
lkjihgfedcba
dcba

```
> 4 votes

# Answer
# V (vim), 15 bytes

```
\Óçá/A¬za
Íˆ…±

```

Try it online!

Hexdump:

```
00000000: 5cd3 e7e1 2f41 ac7a 610d cd88 8185 b1    \.../A.za......

```

Fun fact: Recursion is the only form of looping that V has, yet this submission doesn't use any.
> 4 votes

# Answer
# Befunge-98 (PyFunge), 18 bytes

```
#@~#;:'``j;:,1-;a,

```

Try it online!
> 4 votes

# Answer
# PHP, 88 bytes

```
<?php
for(;$i<strlen($s=$argv[1]);){for($j=ord($s[$i++]);$j>96;)echo chr($j--);echo"
";}

```

Try it online!

Thanks to Shaggy for -21 bytes! :)
> 4 votes

# Answer
# Lua, 94 bytes

```
function r(l)return l:find"[` ]"and"\n"or l..r(l.char(l:byte()-1))end
print((...):gsub(".",r))

```

Try it online!

Only works if we can have redundant output, else +1 byte.

## Explanation

Creates a recursive function `r` that returns what each letter should turn into. When the input letter of this function is a space or the character before `a` (which is \`) then this should not be printed, but a new line instead.

Replace each character in the input string (the first command-line argument) with the output of the function r called with this character.
> 4 votes

# Answer
# Jelly, 7 bytes

```
Øa>Ðḟ)U

```

A monadic link accepting a list of characters which yields a list of lists of characters.

**Try it online!** (adds newlines, since as a full program Jelly will print a smashed version of the lists)

### How?

```
Øa>Ðḟ)U - Link: list of characters, S
     )  - for each (character, c, in S):
Øa      -   yield the lowercase alphabet ['a', 'b', ..., 'z']
   Ðḟ   -   filter discard those for which:
  >     -     greater than (c)?
      U - reverse each resulting list (each line)

```
> 4 votes

# Answer
**Brainfuck, 240 chars**

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

Try it online!

*Explanation:*

, takes an input for the length of the input for the loop

\[\>,\[\>+\>+\<\<-\]\> takes an input and duplicates it

------------------------------------------------------------------------------------------------ takes 97 from the ascii value of the input to iterate over

\[\>.-\<-\] outputs the ascii character and then takes one away from the pointer, ready for the next loop

++++++++++.----------\> outputs the newline

------------------------------------------------------------------------------------------------\<\<\<-\] resets everything ready for another iteration
> 4 votes

# Answer
# Japt `-mR`, 6 bytes

Takes input as an array of characters.

```
;CÔk>U

```

Try it
> 3 votes

# Answer
# GolfScript, ~~27~~ ~~18~~ 17 bytes

```
{),97>-1%10}/]''+

```

Try it online!

Explanation:

```
 {           }/       Iterate over (implicit) input
  ),                  Create array [0 1 2 ... n]
    97>               Remove items less than 97
        -1%           Reverse order
           10         Push 10
               ]      Place in array
                ''+   Convert ascii values to string

```
> 3 votes

# Answer
# SNOBOL4 (CSNOBOL4), 94 bytes

```
	I =INPUT
S	I LEN(1) . X REM . I	:F(END)
	Y =
	&LCASE ARB . Y X
	OUTPUT =X REVERSE(Y)	:(S)
END

```

Try it online!
> 3 votes

# Answer
# Bash, ~~<sup>73</sup>~~ ~~<sup>63</sup>~~ 57 bytes

```
while read -n1 a;do [ - $a]&&echo||eval echo {$a..a};done

```

Try it online!

*-6 bytes thanks to Kritixi Lithos*
> 3 votes

# Answer
# Brachylog, 13 bytes

```
ẹ{;Ẓ↔⟨a₁h⟩|}ᵐ

```

Try it online!

This feels... bad.

```
ẹ{         }ᵐ    For each element of the input,
      a₁         output the suffix of
   Ẓ             the lowercase alphabet reversed
  ; ↔⟨  h⟩       for which the first element is the input,
          |      or the input if there is no such suffix.

```

A 9-byte generator is possible if spaces are completely ignored: `∋;Ẓ↔⟨a₁h⟩`. Accounting for spaces brings it up to the same byte count:

# Brachylog, 13 bytes

```
∋{;Ẓ↔⟨a₁h⟩!|}

```

Try it online!
> 3 votes

# Answer
# Julia 1.0, ~~36~~ 29 bytes

```
f(s)=[join(i:-1:'a') for i=s]

```

Try it online!

Note: Outputs as an array of strings.

To display in a nice output format, use, for example, `println.(f("hello world"))`
> 3 votes

# Answer
# Poetic, 482 bytes

```
transmit a letter or two,a-z
enter in letters from a-z+space
i did a print,i say a letter&go down
i am moving in a cycle
i get to letter a,and maybe to space
i then create lines as i output the ten,a ASCII N/L char
i figure x>y,and i do admire a way i check it
if indeed x>y,then i rerun;if not,i finish it to output N/L char
i write it out&i follow it up until no char i input is here
o,et cetera as i run
i do admit,i do run relatively longish
o,i say,i do loads of BS deriving it

```

Try it online!

Not sure why no one's posted a pure brainfuck solution yet, the brainfuck program I made this poem from amounts to only 108 bytes.
> 3 votes

# Answer
# Scala, 53 bytes

```
def f(s:String)=s.map(c=>('a'to c).reverse.mkString)

```

Try it online!

Note: return the list of strings. To do the actual output, use `.map(println)` or so
> 3 votes

# Answer
# IBM/Lotus Notes Formula, 116 bytes

```
a:="zyxwvutsrqponmlkjihgfedcba";p:="";@For(x:=1;x<=@Length(i);x:=x+1;c:=@Right(@Left(i;x);1);p:=p:(c+@Right(a;c)));p

```

I have never found a practical use for `@For` except when golfing.
> 3 votes

# Answer
## Common Lisp, 127 bytes

Also the first truly recursive answer:

```
(labels((p(x)(princ(code-char x))(if(< 97 x)(p(1- x))(terpri)))(s(s n)(p(char s n))(if(>(length s)n)(s(1+ n))))(x(s)(s 0)))#'x)

```

Test:

```
(funcall (labels((p(x)(princ(code-char x))(if(< 97 x)(p(1- x))(terpri))t)
                 (s(n s)(and(>(length s)n)(p(char-code(char s n)))(s(1+ n)s)))
                 (x(s)(s 0 s)))#'x)
         "hello world")

```

Try it online!

The recursive `p` function prints from an ascii code down to 97, then a newline (terpri) (this also covers the space case since its code is 32).

The recursive `s` function iterates over string `s` by increasing index `n`, calling `p` at each step for the character at position `n`.
> 3 votes

# Answer
# Standard ML (MLton), ~~84~~ 79 bytes

```
fun t#"a"="a"|t#" "=" "|t x=(str x)^t(chr((ord x)-1));fun q p=map t(explode p);

```

Try it online!

Done by coworker, I insisted it should recursive at least partially.

Thanks for -5 to Galen Ivanov!
> 3 votes

# Answer
# Retina, 38 bytes

```
L$`.
27*$&
+T` l`_al`(?<=(.))\1+
aa+
a

```

Try it online! Explanation:

```
L$`.
27*$&

```

List each character 27 times each on its own line.

```
+T` l`_al`(?<=(.))\1+

```

Count all the characters back down to `a`, except the first of each run, and also delete trailing spaces.

```
aa+
a

```

Remove trailing `a`s.
> 3 votes

# Answer
# PHP, ~~68~~ ~~63~~ 55 bytes

Simple approach, similar to my previous answer.

```
for(;$c=$argn[$i++];)echo$c<a?"":join(range($c,a)),"\n";

```

The `\n` was counted as 1 character, not 2 characters.

This is meant to be used with `php -R`.

---

Thanks to @manatwork for saving 5 bytes, and providing the link to try the code: https://tio.run/##BcHRCYAgEADQ/6YQEVSoBSpohxaI6zKvEE9OofHtvRMq9UJFTbuy/WYJgORqk6OW9DRnQGL2UA36gMQGV9i0nl9@shPIMTiDI3g/6kEv3XYKKbH6WNL1Aw

Thanks to @Shaggy for saving another 8 bytes, and providing an updated link: https://tio.run/##BcFBCoAgEADAe68QWVDRPpBFf@gaHTYzNcQVO/R8mznxjb3GysaNiX5TkxbcAthC2SFpfVjlXSRwM66cTw@lIhuW4CU4g0oZPnDbRY8@Z2IftXz9
> 3 votes

# Answer
# , 22 bytes

```
(u:97+i._26)&(i.}.[)"0

```

Try it online!
> 3 votes

# Answer
# Keg, 33 bytes

```
@f1|: =[,|:a=[,|:,;@fƒ]]ƒ?(@fƒ
,)

```

Try it online!

Unlike most people here, this answer actually uses recursion!

# Keg, `-ir` `-lp`, 22 bytes

```
(: >[:&aɧ(&\`-;|,)],
,

```

Try it online!

Iterative approach as suggested by @A
> 3 votes

# Answer
# Matlab / Octave, 25 bytes

```
for i=s['' i-0:-1:97]
end

```

Assumes the input string `s`, prints out to console.

* Iterate over the contents of the string with `for i=s`
* `i-0` implicitly converts char to number
* `num:-1:97` outputs the range descending from the number down to 97 (ascii a)
* space results in empty output as it already is less than 97
* `['' int]` concatenates an empty char with a number, resulting in a char (saves one byte compared to `char(num)`.
* each loop iteration output is printed as a line to console, which is what Matlab does when there is no semicolon terminating the line.

Try it online!
> 3 votes

# Answer
# Forth (gforth), 66 bytes

```
: f bounds do i c@ dup 96 - 0 max 0 ?do dup emit 1- loop cr loop ;

```

Try it online!

### Code Explanation

```
: f            \ start a new word definition
  bounds       \ get starting and ending address of string
  do           \ loop from starting address to ending address
    i c@       \ get ascii value at current address
    dup 96 -   \ get numerical position in alphabet
    0 max      \ if negative (char is space), set to 0
    0 ?do      \ loop from 0 to position in alphabet
      dup emit \ output character
      1-       \ subtract 1 from current character (move backwards in alphabet)
    loop       \ end inner loop definition
    cr         \ output a newline
  loop         \ end outer loop definition
;              \ end word definition

```
> 3 votes

# Answer
# brainf\**k 123 bytes

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

```

Try it online!

Not better than the other brainfuck solutions posted in the comments, but still too much work not to post it ;-) In contrast to the bf solutions above, this does not need a circular cell ring.

# How it works

```
p0
,
[  {input}
p1 >
p2 > [-] < ----[---->+<]>+< #64
p3 ++++[->>++++++++<<]  #32
p1 ++++++++++ # 10
p2 >
p3 >
   [
     -
p2   <
p1   <
p0   < -
p1   >
p2   >
p3   >
p4   > +
p3   <
   ]
p2 <
p1 <
p0 <
   [
     -
p1   >
p2   > -
p3   >[-]+ # indicates that output is required
p4   > +
p3   <
p2   <
p1   <
p0   <
   ]
p1 >
p2 >
p3 >  # if output required
   [
     -
p2   <
     [
       +
p3     >
p4     > . -
p3     <
p2     <
     ]
p3   >
   ]
p2 <
p1 < . [-]
p2 >
p3 >
p4 > [-]
p3 <
p2 <
p1 <
p0 < ,
]

```
> 3 votes

# Answer
# naz, 104 bytes

```
2a2x1v2m8m2x2v3m1a2x3v1x1f3x1v4e3x2v3e1o2f0x1x2f3x3v3e1s1o2f0x1x3f1r3x1v4e2x4v0m9a1a1o4v1f0x1x4f0a0x1r1f

```

Works for any input string terminated with the control character STX (U+0002).

If an extra trailing newline is allowed, we can save another 14 bytes:

```
2a2x1v2m8m2x2v3m1a2x3v1x1f1r3x1v4e3x2v3e1o2f0x1x2f3x3v3e1s1o2f0x1x3f0m9a1a1o1f0x1x4f0a0x1f

```

**Explanation of the 104-byte version** (with `0x` commands removed)

```
2a2x1v                       # Set variable 1 equal to 2
2m8m2x2v                     # Set variable 2 equal to 32 (space)
3m1a2x3v                     # Set variable 3 equal to 97 ("a")
1x1f3x1v4e3x2v3e1o2f         # Function 1
                             # Jump to function 4 if the register equals variable 1
                             # Jump to function 3 if the register equals variable 2
                             # Otherwise, output and jump to function 2
1x2f3x3v3e1s1o2f             # Function 2
                             # Jump to function 3 if the register equals variable 3
                             # Otherwise, subtract 1, output,
                             # and jump back to the start of the function
1x3f1r3x1v4e                 # Function 3
                             # Read a byte
                             # Jump to function 4 if it equals variable 1
            2x4v             # Otherwise, store it in variable 4,
                0m9a1a1o     # output a newline,
                        4v1f # read variable 4 into the register, and jump to function 1
1x4f0a                       # Function 4
                             # Add 0 to the register
1r1f                         # Read the first byte of input and jump to function 1

```
> 3 votes

# Answer
# Lua, ~~107~~ 103 bytes

```
s=string
for n in io.read():gmatch"."do t=''for j=s.byte(n)-96,1,-1 do t=t..s.char(j+96)end print(t)end

```

Try it online!

Again, still a newbie to this.
> 2 votes

# Answer
# Perl 5 (`-nF//`), ~~31~~, 28 bytes

-3 bytes thanks to @nwellnhof

```
say/\w/&&reverse a..$_ for@F

```

Try it online!
> 2 votes

# Answer
# Charcoal, 9 bytes

```
ＥＳ⮌…β⊕⌕βι

```

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

```
 Ｓ          Input string
Ｅ           Map over characters
    β       Lowercase alphabet
   …        Truncated to length
      ⌕     Position of
        ι   Current charcter in
       β    Lowercase alphabet
     ⊕      Incremented
  ⮌         Reversed
             Each prefix implicitly printed on its own line

```
> 2 votes

# Answer
# Python 2, 68 bytes

```
for x in input():
 o="";c=ord(x)
 while c>96:o+=chr(c);c-=1
 print o

```

Try it online!

Nothing very clever here.

# Python 2, ~~64~~ 53 bytes

```
lambda i:[map(chr,range(x,96,-1))for x in map(ord,i)]

```

Try it online!

Here's one for ~~64~~ 53 but it outputs a list of lists which is not only ugly but probably stretches "flexible input/output" to near breaking point.
> 2 votes

# Answer
# Kotlin, 56 bytes

```
{it.map{println(('a'..it).joinToString("").reversed())}}

```

Try it online!
> 2 votes

# Answer
# jq, 39 characters

```
explode|map([range(.;96;-1)]|implode)[]

```

Or remove the trailing `[]` to get the output as array of strings.

Sample run:

```
bash-5.0$ jq -Rr 'explode|map([range(.;96;-1)]|implode)[]' <<< 'cgcc'
cba
gfedcba
cba
cba

```

Try it online!
> 2 votes

# Answer
# Pyth, 7 bytes

```
m_<GhxG

```

Try it online!

Lowercase alphabet autos feel like cheating but oh well. Might add a recursive solution if I come up with anything good. Returns list of strings.

## How it works

```
m_<GhxG
m         - Map on implicit input
 _        - The reverse of
  <G      - The lowercase alphabet at and below
     xG   - The index of the implicit element of input in the lowercase alphabet
    h     - above + 1

```
> 2 votes

# Answer
# Red, 56 bytes

```
func[s][foreach c s[until[prin c#"a"> c: c - 1]print""]]

```

Try it online!
> 2 votes

# Answer
# Icon, 66 bytes

```
procedure f(s)
c:=ord(!s)&write()&writes(char(c to 97by-1))&\z
end

```

Try it online!

## Longer alternative:

# Icon, 72 bytes

```
procedure f(s)
c:=ord(!s)-95&write((0>c&"")|reverse(&lcase[1:c]))&\z
end

```

Try it online!
> 2 votes

# Answer
# SimpleTemplate, ~~46~~ 66 bytes

This was a simple challenge, but quite fun!

```
{@eachargv.0}{@echol}{@if_ matches"@\w@"}{@forfrom _to"a"}{@echo_}

```

Loops over all the chars (that match with `\d`) in the string, and then outputs all the characters from that char to "a".

---

**Ungolfed**:

```
{@each argv.0 as char}
    {@echo "\n"}
    {@if char matches "@^[a-z0-9_]$@"}
        {@for letter from char to "a"}
            {@echo letter}
        {@/}
    {@/}
{@/}

```

The `argv` variable contains all the arguments passed to the `render()` method, or to the function, when converted.

The `{@echo "\n"}` (`{@echol}` in the golfed version) is needed because all whitespace will be automatically trimmed.

You can try the golfed version on https://ideone.com/Ru8shP
> 2 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~80~~ 77 bytes

```
a=>{var b="";foreach(var c in a){for(var j=c;j>96;)b+=j--;b+="\n";}return b;}

```

Try it online!

-3 bytes thanks to @my pronoun is monicareinstate for pointing out some unnecessary stuff
> 2 votes

# Answer
# Rust, 63 bytes

```
|s:&str|s.bytes().map(|c|(b'a'..=c).rev()).collect::<Vec<_>>();

```

Try it online!
> 2 votes

# Answer
# Perl 5 \+ `-a -M5.010`, 23 bytes

```
say reverse a..$_ for@F

```

Try it online!
> 2 votes

# Answer
## , ~~7~~ 5 bytes

Lowercase alphabet auto feels like cheating. This one does not use any alphabet built-in with the same bytecount. DISCLAIMER: insert literal spaces as `\x20` in your input strings.

```
^'a.E

```

## Explanation

```
   E Map over every item in the input
^    Trim out all literal whitespace in this item
 'a. Generate a range to the character 'a'
     An error-proof mechanism returns the null string
     if any of those operands are the null string
     Implicit print on each iteration

```
> 2 votes

# Answer
# Pip `-l`, 11 bytes

```
CRV97\,A_Ma

```

Try it online!

### Explanation

```
          a  Input as a command-line argument
         M   Map this function to each of its characters:
       A_     Get ASCII code
   97\,       Range from 97 up to and including the above
 RV           Reverse the range
C             Convert to (a list of) characters
             With -l, output each list of chars concatenated on separate lines

```
> 2 votes

# Answer
# TCL, 179 bytes

```
rename string d;proc a s {set b zyxwvutsrqponmlkjihgfedcba;if {$s=={}} return;if {[set c [d first [d index $s 0] $b]]<0} {puts {}} {puts [d range $b $c end]};a [d replace $s 0 0]}

```

Try it online!

ungolfed version

```
proc a {s} {
    set b zyxwvutsrqponmlkjihgfedcba
    if {$s=={}} return

    if {[set c [string first [string index $s 0] $b]]<0} then {
            puts {} # if it's a space print a newline
    } else {
        puts [string range $b $c end] # print the substring of $b starting at the character
    }

    #recurse on the string minus the front character
    a [string replace $s 0 0]
}

a [concat $argv]

```
> 2 votes

# Answer
# Burlesque, 13 bytes

```
XX{'ajr\<-}m[

```

Try it online!

```
XX  # Explode a string into characters
{
'a  # Literal "a"
jr\ # Create range from "a" -> char and join as string
<-  # Reverse string
}m[ # Apply to each char

```
> 2 votes

# Answer
# Python 3, ~~76~~ ~~60~~ 53 bytes

## (thanks to @Jo King & @sporeball)

```
for a in input():print(*map(chr,range(ord(a),96,-1)))

```

Try it online! (original 76 bytes solution)

Try it online! (53 bytes solution)
> 2 votes

# Answer
# x86-16 machine code, IBM PC DOS, ~~27~~ 23 bytes

**Binary:**

```
00000000: b408 cd21 b40e cd10 483c 617d f9b0 0acd  ...!....H<a}....
00000010: 10b0 0dcd 10eb e9                        .......

```

Test and build using `xxd -r` from above.

**Unassembled:**

```
        IN_LOOP:
B4 08       MOV  AH, 08H        ; DOS read char without echo function
CD 21       INT  21H            ; load next char from STDIN
B4 0E       MOV  AH, 0EH        ; BIOS write char teletype output function
        CHR_LOOP:
CD 10       INT  10H            ; write to console
48          DEC  AX             ; move to next char
3C 61       CMP  AL, 'a'        ; end with an 'a'
7D F9       JGE  CHR_LOOP       ; keep looping descending chars
B0 0A       MOV  AL, 0AH        ; CR char
CD 10       INT  10H            ; write to console
B0 0D       MOV  AL, 0DH        ; LF char
CD 10       INT  10H            ; write to console
EB E9       JMP  IN_LOOP        ; keep looping until ^C/^Break

```

**I/O:**

Input via `STDIN` or interactive input, output to console. Will run until `EOF` or `^C/^Break`.

Iterative approach. Of course, it's **8 bytes** just to write a newline character...
> 2 votes

# Answer
# Husk, ~~8~~ 6 bytes

<sup>*-2 bytes thanks to Dominic van Essen!*</sup>

```
†`…'aw

```

Try it online!
> 2 votes

# Answer
# Vyxal `jr`, 6 bytes

```
ƛkzẆḢṅ

```

Try it Online!

Flags are unintentional. -5 thanks to tybocopperkettle.

```
ƛ      # For each character
   Ẇ   # Split, keeping the delimeter
 kz    # The lowercase alphabet, backwards
   Ẇ   # On that character
    Ḣ  # Remove the first string (all letters before that character)
     ṅ # Concatenate the remaining strings.

```
> 2 votes

# Answer
# Factor, 35 bytes

```
[ [ dup 97 min [a,b] print ] each ]

```

Pointlessly indeed.

Attempt This Online!
> 2 votes

# Answer
# Arturo, 27 bytes

```
$=>[map&'c->@c..min@[c`a`]]

```

Try it!

Outputs a list of lists of characters.
> 2 votes

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

```
M'+[\/ +x]\xczcn

```

I haven't done any Fig (or any code golf for that matter) in ages so this can probably be golfed a lot...

Try it online!

Explanation:

```
M                 # Map over each character in the input
 '                # a function from the following code:
          \       #   split
            cz    #   the reversed alphabet
           x      #   on the current character,
         ]        #   get the last item from that list (e.g. "gfedcba" for "h"),
       +          #   add that to
        x         #   the current character, (we now have "hgfedcba")
    \             #   split that on
     /            #   spaces, (if the char is a space we need to remove the whole reversed alphabet which would've just been appended to it)
   [              #   get the first item from that,
  +               #   append
              cn  #   a newline.
                  # Implicitly print joined by nothing.

```
> 2 votes

# Answer
# Ruby, 40 bytes

```
ARGV[0].chars.map{|c|print *'a'..c;puts}

```

Try it online!
> 1 votes

# Answer
# Pushy, 22 bytes

```
N@$'&32!?&97-:t';;T'..

```

Try it online!

```
N@$'&32!?&97-:t';;T'..

N                       \ Set output delimiter to empty string
 @                      \ Reverse input
  $                     \ While there are characters left on stack:
   '                    \   Print the top character
    &32!?        ;       \   if not a space:
         &97-:  ;       \     char(top) - 97 times do:
              t'        \       Decrement character and print
                  T'    \   Print a newline
                    ..  \   Clear up stack (pops items we are done with)

```
> 1 votes

# Answer
# Standard ML (MLton), 62 bytes

```
fun$c=if#"a">c then""else str c^ $(Char.pred c);map$o explode;

```

Defines an anonymous function which is implicitly bound to `it`, so use as e.g. `it "hello world"`: Try it online! Based on Thoma's SML answer.

### Explanation

```
fun down c = if #"a" > c then "" else str c ^ t(Char.pred c)
val it = map down o explode

```

The function `down` takes a character `c` and recursively (!) builds the string of previous letters. The point-free function bound to `it` first `explode`s a given string into a list of characters and applies `down` to each of them.
> 1 votes

# Answer
# PowerShell, 47 bytes

```
$args|% T*y|%{($_,(-join($_..'a')))[!!($_%32)]}

```

Try it online!

# PowerShell 7, 38 bytes

```
$args|% T*y|%{$_%32?-join($_..'a'):$_}

```

No TIO link because TIO does not support PS7 yet.

# PowerShell (Splatted Input), 41 bytes

Takes the input as an array of characters; not sure if this is legal for this challenge, so I've broken it into a separate section.

```
$args|%{($_,(-join($_..'a')))[!!($_%32)]}

```

Try it online!

# PowerShell 7 (Splatted Input), 32 bytes

Takes the input as an array of characters; not sure if this is legal for this challenge, so I've broken it into a separate section.

```
$args|%{$_%32?-join($_..'a'):$_}

```

No TIO link because TIO does not support PS7 yet.
> 1 votes

# Answer
# Zsh, 49 bytes

```
>\
for c (${(s"")1})<$c||printf %s {$c..a}&&echo
```

Attempt This Online!
> 1 votes

# Answer
# Thunno 2, 4 bytes

```
ẠḲṣṆ

```

Attempt This Online!

Port of Kevin Cruijssen's (bottom) 05AB1E answer.

## Thunno 2, 5 bytes

```
ẠDƒṃṆ

```

Attempt This Online!

Port of Kevin Cruijssen's (top) 05AB1E answer.

#### Explanation

```
ẠḲṣṆ  # Implicit input
Ạ     # Lowercase alphabet
 Ḳ    # Bifurcate
  ṣ   # Suffixes
   Ṇ  # Transliterate
      # Implicit output

```

```
ẠDƒṃṆ  # Implicit input
Ạ      # Lowercase alphabet
 Dƒ    # Duplicate and get prefixes
   ṃ   # Reverse each item
    Ṇ  # Transliterate
       # Implicit output

```
> 1 votes

# Answer
# Python, 73 Bytes

```
lambda x:'\n'.join(''.join(chr(y)for y in range(ord(z),96,-1))for z in x)

```

Anonymous lambda function that returns a string. If you want one that works for only capital letters, you only need to change `96` to `64`.

tsrqponmlkjihgfedcbarqponmlkjihgfedcbayxwvutsrqponmlkjihgfedcbaihgfedcbatsrqponmlkjihgfedcbaonmlkjihgfedcbanmlkjihgfedcbalkjihgfedcbaihgfedcbanmlkjihgfedcbaedcba
> 1 votes

# Answer
# Ruby `-n`, 35 bytes

```
$_.chars{puts [*?a.._1].reverse*""}

```

Attempt This Online!
> 1 votes

# Answer
# Rockstar, 111 bytes

```
listen to S
cut S
while S
cast roll S in C with 36
O's ""
while C-9
cast C+87 in N
let O be+N
let C be-1

say O

```

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

---
Tags: code-golf, alphabet, recursion
---


# Question
Title: List of possible birth years of living humans
**The Challenge**

Output a list of years that starts with the current year and ends 120 years ago. The birth year of every living human would be included in this list.

**Details**

The list should be in descending order.

Every built-in function to manipulate arrays and/or lists is allowed.

Shortest code in bytes wins.

When run this year `2016`, the output would be

`2016, 2015, ..., 1897, 1896`

When run next year `2017`, the output would be

`2017, 2016, ..., 1898, 1897`

Etc.

**Update**

* Some have asked about the format of the list. As most have guessed, it doesn't matter. Insert any separator between the numbers. Intuitively most inserted a comma or space or both, newline or output an array.
* Quasi superhumans like Jeanne Calment are an exception to the rule stated in my question.

# Answer
> 19 votes
## Pyke, 6 bytes

```
wC7m-

```

Try it here!

```
w     - 121
   m- - for i in range(^):
 C7   -  current_year-i

```

(After `w`, the codepoint for 153 is present but it isn't printable)

# Answer
> 11 votes
# Pyth, ~~11~~ ~~9~~ 8 bytes

```
-L.d3C\y

```

Works by mapping over the range `[0...120]` and subtracting every number from the current year. The range is built implicitly by using `121` as the map argument. To avoid a separating whitespace between `.d3` and `121` we get this number by converting `y` to it's codepoint.
Thanks to @FryAmTheEggman for coming up with this approach!

Try it here!

***Old 9-byte solution:***

```
_>121S.d3

```

Try it here!

Builds the range `[1...<current year>]` and only takes the last 121 elements of it.

# Answer
> 9 votes
# R, 34 bytes

```
(format(Sys.Date(),"%Y"):0)[1:121]

```

See here on an online interpreter.

**Edit** Could be reduced to 33 bytes by using `substr`.

```
(substr(Sys.Date(),1,4):0)[1:121]

```

but technically this solution will only work until the 9999-12-31.

# Answer
> 8 votes
# BASH + coreutils, ~~35~~ 33 bytes

```
x=`date +%Y`;seq $x -1 $((x-120))

```

# Answer
> 8 votes
# AngularJS \+ Lodash, 274 bytes

```
angular.module('x',[]).controller('x',['$scope',function(x){x.x=_.range(9,new Date().getFullYear()+1).slice(-121).reverse()}])
```

```
<script src=//goo.gl/M5LvGe></script><script src=//goo.gl/opljJl></script><select ng-app=x ng-controller=x multiple><option ng-repeat="x in x">{{x}}
```

Output

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

*Saved 2 bytes thanks to Sp3000 and 1 byte thanks to Martin Ender*

```
et0=121,f-p

```

Try it online!

**Explanation**

```
et0=         e# Push the current year
    121,     e# Push the range 0, 1, ..., 120
        f-   e# For each item in the range, subtract it from current year
          p  e# Print the array

```

# Answer
> 7 votes
# HP50g RPL, 97 bytes

```
120 'S' STO DATE ->STR 6 9 SUB OBJ-> 'Y' STO {} S WHILE 0 >= REPEAT Y S - + 'S' DECR END REVLIST

```

Ungolfed:

```
120
'span' STO     @ Store the span of years to cover.
DATE           @ Get the date as number 11.082016.
→STR           @ Convert to string "11.082016".
               @ (Number format must allow all these decimal places.)
6 9 SUB        @ "11.082016" Substring for the year.
               @       ^  ^
               @  123456789
OBJ→           @ Convert string to number.
'year' STO     @ Store as the year to start at.
{} span        @ Start empty list to collect the years.
               @ Leave loop counter on the stack.
WHILE 0 ≥      @ Loop until the counter goes negative.
REPEAT
  year span -  @ E.g. on first iteration: 2016 - 120 = 1896.
  +            @ Append the year to the list on the stack.
  'span' DECR  @ Decrement loop counter and leave on stack.
END
REVLIST        @ Put list in reverse chronological order.

```

Showing a list of 2016 down to 1896:

# Answer
> 6 votes
# Dyalog APL, ~~11~~ 10 bytes

```
120↑⌽⍳⊃⎕ts

```

`120↑` take 120 elements

of the reversed

indices until

the first element of

`⎕TS` TimeStamp in the format \[YYYY, M, D, h, m, s, t\]

TryAPL online!

---

Old version:

```
(⊃⎕TS)-⍳120

```

`⊃⎕TS` first element of \[YYYY, M, D, h, m, s, t\]

`-` minus

`⍳120` \[0, 1, 2, ..., 118, 119\]

Requires `⎕IO←0`, which is default on many systems.

TryAPL online!

# Answer
> 6 votes
# 05AB1E, ~~8~~ 7 bytes

Code:

```
žg120Ý-

```

Explanation:

```
žg         # Get the current year.
  120Ý     # Create the list [0, 1, ..., 119, 120].
      -    # Substract, which leaves [year - 0, year - 1, ..., year - 120].

```

Uses the **CP-1252** encoding. Try it online!.

# Answer
> 6 votes
# PowerShell, 26 24 bytes

@TimmyD improved version:

```
0..120|%{(date).Year-$_}

```

Was:

```
($d=(date).year)..($d-120)

```

where `date` runs `Get-Date`

# Answer
> 6 votes
# Vitsy \+ \*sh ~~\+ JavaScript~~, ~~33~~ ~~26~~ ~~21~~ 18 bytes

Vitsy doesn't have native time/date retrieval, so I had to use shell and eval for this one.

Thanks to @Caleb for helping me shear off another 3 bytes!

```
'Y%+ etad',Dca*-HZ

'Y%+ etad'               Push the string 'date +"%Y"' to the stack.
          ,              Execute through shell.
           Dca*-         Dupe n, push n - 120.
                H        Pop x, y, push range(x, y) to the stack.
                 Z       Output all stack as characters.

```

You can't try this one online, because it uses both shell AND eval.

Output is as character codes.

# Answer
> 5 votes
## R, ~~47~~ 39 bytes

```
as.double(substr(Sys.Date(),1,4))-0:120

```

If only someone invented a UTF-8 implementation of R with conveniently abbreviated frequently used system functions...

UPD: shaved off 7 (!) bytes owing to plannapus, who suggested subrtacting a `0:120` vector rather than counting from `a` to `(a-120)` and 1 byte grâce à user5957401, who noticed that `double` would work as well as `numeric`. Old version:

```
a=as.numeric(format(Sys.Date(),"%Y"));a:(a-120)

```

# Answer
> 5 votes
# MATL, 10 bytes

```
1&Z'0:120-

```

**Try it online!**

```
1&Z'      % Push first component of "clock" vector, which is year
0:120     % Literal vector [0, 1, 2, ..., 120]
-         % Subtract element-wise. Implicitly display

```

# Answer
> 5 votes
**Mathematica/Wolfram Language, 28 bytes**

```
Date[][[1]]-#&/@Range[0,120]

```

# Answer
> 5 votes
# 05AB1E, 9 bytes

`121FžgN-=`

Try online

# Answer
> 4 votes
## Python 2, ~~64 62~~ 54 bytes

```
import time
n=time.gmtime()[0]
exec'print n;n-=1;'*121

```

@KarlKastor thanks for 8 bytes!

# Answer
> 4 votes
# php, 73 66 58 42 bytes

```
<?=implode(', ',range($j=date(Y),$j-120));

```

## Output:

> 2016, 2015, 2014, 2013, 2012, 2011, 2010, 2009, 2008, 2007, 2006, 2005, 2004, 2003, 2002, 2001, 2000, 1999, 1998, 1997, 1996, 1995, 1994, 1993, 1992, 1991, 1990, 1989, 1988, 1987, 1986, 1985, 1984, 1983, 1982, 1981, 1980, 1979, 1978, 1977, 1976, 1975, 1974, 1973, 1972, 1971, 1970, 1969, 1968, 1967, 1966, 1965, 1964, 1963, 1962, 1961, 1960, 1959, 1958, 1957, 1956, 1955, 1954, 1953, 1952, 1951, 1950, 1949, 1948, 1947, 1946, 1945, 1944, 1943, 1942, 1941, 1940, 1939, 1938, 1937, 1936, 1935, 1934, 1933, 1932, 1931, 1930, 1929, 1928, 1927, 1926, 1925, 1924, 1923, 1922, 1921, 1920, 1919, 1918, 1917, 1916, 1915, 1914, 1913, 1912, 1911, 1910, 1909, 1908, 1907, 1906, 1905, 1904, 1903, 1902, 1901, 1900, 1899, 1898, 1897, 1896

If we don't need to separate with `,`, then 58 57 41 bytes:

```
<?=implode(' ',range($j=date(Y),$j-120));

```

Thanks to insertusernamehere for saving 16 bytes

# Answer
> 4 votes
# PostgreSQL, 57 bytes

Who needs a `FROM` :-). Probably shouldn't work, but it does, try it at sqlfiddle

```
select date_part('y',current_date)-generate_series(0,120)

```

# Answer
> 4 votes
# Bash on OS X, 23

```
jot 121 `date +%Y` - -1

```

This will also work on Linux if you have BSD `jot` installed (e.g. `sudo apt-get install athena-jot`.

# Answer
> 3 votes
## Python 2, 62 bytes

```
import time
for n in range(121):print int(time.ctime()[-4:])-n

```

And at 64 bytes:

```
for n in range(121):print int(__import__("time").ctime()[-4:])-n

```

# Answer
> 3 votes
## JavaScript, ~~55~~ ~~52~~ ~~50~~ 49 bytes

```
for(a=d=s=Date().substr(11,4);d-->s-120;)a+=" "+d

```

+9 bytes to `alert` the data (not necessary if you run this in a console).

```
for(a=d=s=Date().substr(11,4);d-->s-120;)a+=" "+d;alert(a)

```

-4 bytes if the delimiter isn't necessary.

```
for(a=d=s=Date().substr(11,4);d-->s-120;)a+=d

```

```
for (a = d = s = Date().substr(11, 4); d --> s - 120; )
    a += " " + d;
console.log(a);
```

# Answer
> 3 votes
# Oracle SQL 11.2, 111 bytes

```
SELECT LISTAGG(TO_CHAR(SYSDATE,'YYYY')-LEVEL+1,', ')WITHIN GROUP(ORDER BY LEVEL)FROM DUAL CONNECT BY LEVEL<122;

```

# Answer
> 3 votes
## C, ~~87~~ ~~85~~ ~~76~~ ~~74~~ 65 bytes

```
main(int i,char**v){for(i=0;i<121;printf("%d,",atoi(v[1])-i++));}

```

Ungolfed:

```
main(int i,char**v){
    for(i = 0; i < 121; printf("%d,", atoi(v[1])-i++));
}

```

My first code golf - Any pointers would be well received. Would be nice if I could cut out the argc/argv junk, but I'm not *that* skilled a C programmer. Improvements welcome.

**EDIT**: The current year is obtained from the commandline - specifically by a group of automated, well trained drinking birds.

**EDIT 2**: 85 bytes Thanks to Easterly Irk (removed spaces around arg function parameters)

**EDIT 3**: 76 bytes Thanks to anatolyg for pointing out the obvious (removed verbose argc/argv param names)

**EDIT 4**: 74 bytes Thanks to Yay295 (char\**v, changed year delimiter)

**EDIT 5**: 65 bytes thanks to Yay295 and matt (re-used the variable i, removed variable x, changed while to for loop, updated printf to include atoi() read and i++)

# Answer
> 3 votes
# Processing, ~~51~~ ~~42~~ 41 bytes

```
for(int i=0;i<121;)print(year()-i+++" ");

```

# Ungolfed

```
for(int i = 0; i < 121;)
    print(year() - i++ + " ");

```

Processing is just a wrapper for Java if you didn't know, and takes most of the boilerplate away, so the obvious solution is also super short compared to a Java version. Also opens a window for drawing graphics, but having that doesn't appear to disqualify me :)

# Answer
> 3 votes
# MATLAB, 18 bytes

Assuming the output format doesn't matter (aside form descending order), the following program prints the last 121 years starting with the current one.

```
year(date)-(0:120)

```

It requires MATLAB version r2014a or higher. Earlier versions didn't include the `year` function.

# Answer
> 3 votes
# **JavaScript, ~~60~~ ~~53~~ 48 Bytes**

```
f=x=>x>Date().split` `[3]-121&&(alert(x),f(x-1))

```

I used a recursive solution.

# Answer
> 3 votes
# Go, 71 bytes

```
import."time"
func f(){for t,i:=Now().Year(),0;i<120;i++{println(t-i)}}

```

Attempt This Online!

Prints to STDERR.

# Answer
> 2 votes
## Perl, 33 bytes

```
say+(gmtime)[5]-$_+1900for 0..120

```

Run with `-M5.010` or `-E` :

```
perl -E 'say+(gmtime)[5]-$_+1900for 0..120'

```

# Answer
> 2 votes
# k, 27 bytes

Output as specified

```
1@", "/:$(`year$.z.d)-!121;

```

Example:

```
k)1@", "/:$(`year$.z.d)-!121;
2016, 2015, 2014, 2013, 2012, 2011, 2010, 2009, 2008, 2007, 2006, 2005, 2004, 2003, 2002, 2001, 2000, 1999, 1998, 1997, 1996, 1995, 1994, 1993, 1992, 1991, 1990, 1989, 1988, 1987, 1986, 1985, 1984, 1983, 1982, 1981, 1980, 1979, 1978, 1977, 1976, 1975, 1974, 1973, 1972, 1971, 1970, 1969, 1968, 1967, 1966, 1965, 1964, 1963, 1962, 1961, 1960, 1959, 1958, 1957, 1956, 1955, 1954, 1953, 1952, 1951, 1950, 1949, 1948, 1947, 1946, 1945, 1944, 1943, 1942, 1941, 1940, 1939, 1938, 1937, 1936, 1935, 1934, 1933, 1932, 1931, 1930, 1929, 1928, 1927, 1926, 1925, 1924, 1923, 1922, 1921, 1920, 1919, 1918, 1917, 1916, 1915, 1914, 1913, 1912, 1911, 1910, 1909, 1908, 1907, 1906, 1905, 1904, 1903, 1902, 1901, 1900, 1899, 1898, 1897, 1896

```

It can be shortened more by not formatting the output and merely returning the list of integers:

```
(`year$.z.d)-!121

```

# Answer
> 2 votes
# Fourier, 17 bytes

```
121(5d-io10ai^~i)

```

Since no output format is specified, each year is separated by a newline:

Try it online

# Answer
> 2 votes
# jq, 46 characters

(45 characters code + 1 character command line option)

```
now|strftime("%Y")|tonumber|range(.;.-121;-1)

```

Sample run:

```
bash-4.3$ jq -n 'now|strftime("%Y")|tonumber|range(.;.-121;-1)' | head
2016
2015
2014
2013
2012
2011
2010
2009
2008
2007

```

On-line test

# Answer
> 2 votes
## Vim, ~~32~~ 29 keystrokes

Thanks to @daniero for some help on saving some keystrokes and making the output a little neater.

```
"=strftime('%Y')<Enter>pqqYp<Ctrl-x>q118@q

```
* `<Enter>` is `Enter`
* `<Ctrl-x>` is `Ctrl` \+ `X`

### Explanation:

```
"                                          # Put into the register {
 =strftime('%Y')                           #   This year in YYYY form
                <Enter>                    # }
                       p                   # Paste the register
                        qq                 # Record macro q {
                          Y                #   Yank (copy) the current line
                           p               #   Paste
                            <Ctrl-x>       #   Decrment number at cursor
                                    q      # }
                                     118@q # Do macro q 118 times

```

### Output format:

Each number is on a separate line like below.

```
2016
2015
.
.
.
1898
1897

```

# Answer
> 2 votes
## PHP, 40 35 33 bytes

```
while($i<121)echo date(Y)-$i++._;

```

I'm just going to pretend that error reporting is always disabled for code golfing... :)

\[Edit 1: Saved 5 bytes via manatwork\]

\[Edit 2: Saved 2 bytes via Titus\]

# Answer
> 2 votes
# LaTeX, 129 bytes

Or, if I'm allowed to skip the document class definition & setup, and just count the package import and for loop code: **79 bytes**.

```
\documentclass{book}\usepackage{tikz}\begin{document}\foreach \n in {0,...,120}{\pgfmathint{\year\n}\pgfmathresult}\end{document}

```

Ungolfed:

```
\documentclass{book}
\usepackage{tikz}
\begin{document}
\foreach \n in {0,...,120}
{
\pgfmathint{\year-\n}\pgfmathresult}

\end{document}

```

Output (w/ free page number :) ):

# Answer
> 2 votes
# Japt, 12 6 bytes

*Saved 6 bytes thanks to @ETHproductions*

```
#yonKi

```

Try it online!

### Explanation:

```
#yonKi
#y          // # gets the char-code of y, which is 121
  o         // Create a range from [0...121]
   nKi      // At each item, perform .n(K.i()), which subtracts each item from Ki (Current year)

```

# Answer
> 2 votes
# Minim, 49 Bytes

Program is run as follows:

```
C:\Users\chris> minim -f golf.min

```

Golfed:

```
[]="xyear".\<1.\>[1].#<[1]--i.$<32._^!--[0].C-=4.

```

With whitespace and comments:

```
[] = "xyear".  ; Insert the string 'xyear' into memory from index 0 \
                 The 'x' character corresponds to the value '120'
\< 1.          ; Insert 1 as a system call argument \
                 This corresponds to the index in memory of the \
                 function name to call, 'year'
\> [1].        ; Call the function and insert the result at memory index 1
    #< [1]--i. ; Print memory index 1 as an integer, post-decremented
    $< 32.     ; Print a space
    _^ !--[0]. ; Skip the next statement if memory index 0, pre-decremented, is 0
C -= 4.        ; Subtract 4 from the program counter

```

GitHub Repository

# Answer
> 1 votes
# JavaScript (ES6), 65 bytes

`[...Array(1+- -Date().substr(11,4)).keys()].slice(-121).reverse()`

You're welcome to improve and shorten it...

Thanks to @Yay295 for the fix. I was 1 year off.

# Answer
> 1 votes
# Python 2, 67 bytes

```
from datetime import*;for i in range(121):print date.today().year-i

```

Thanks to Sp3000 for removing one byte

# Answer
> 1 votes
### VBA, 54 bytes

In the *immediate pane*:

```
For i=0 To 120:?Year(Date)-i &IIf(i=120,"",", ");:Next

```

---

In an actual `Sub` procedure (the VBE adds whitespace and changes `?` to `Print`, but the code is per language specs without the whitespace and using the `?` shorthand nonetheless):

```
Sub A()
For i = 0 To 120: Print Year(Date) - i & IIf(i = 120, "", ", ");: Next
End Sub

```

That's 88 characters per Notepad++, with `i` being an undeclared, implicit `Variant` local variable.

Both produce the output exactly as specified in the question, comma-separated and with a space between each year:

```
2016, 2015, 2014, 2013, 2012, 2011, 2010, 2009, 2008, 2007, 2006, 2005, 2004, 2003, 2002, 2001, 2000, 1999, 1998, 1997, 1996, 1995, 1994, 1993, 1992, 1991, 1990, 1989, 1988, 1987, 1986, 1985, 1984, 1983, 1982, 1981, 1980, 1979, 1978, 1977, 1976, 1975, 1974, 1973, 1972, 1971, 1970, 1969, 1968, 1967, 1966, 1965, 1964, 1963, 1962, 1961, 1960, 1959, 1958, 1957, 1956, 1955, 1954, 1953, 1952, 1951, 1950, 1949, 1948, 1947, 1946, 1945, 1944, 1943, 1942, 1941, 1940, 1939, 1938, 1937, 1936, 1935, 1934, 1933, 1932, 1931, 1930, 1929, 1928, 1927, 1926, 1925, 1924, 1923, 1922, 1921, 1920, 1919, 1918, 1917, 1916, 1915, 1914, 1913, 1912, 1911, 1910, 1909, 1908, 1907, 1906, 1905, 1904, 1903, 1902, 1901, 1900, 1899, 1898, 1897, 1896

```

---

If the commas aren't a requirement (as some other answers seem to presume), then the `IIf` part can be dropped, cutting the *immediate pane* code down to **33 bytes**:

```
For i=0 To 120:?Year(Date)-i:Next

```

# Answer
> 1 votes
## ListSharp, 71 bytes

```
NUMB a=<c#DateTime.Now.Yearc#>
[FOREACH NUMB IN a TO a-120 AS y]
SHOW=y

```

Uses embedded c# code, *new feature!!*

# Answer
> 1 votes
# Nim, 60 bytes

```
import times
for a in 0..120:echo getTime().getGmTime.year-a

```

Outputs each year on a new line. We use the `getTime` to get the current UNIX time, then convert it to UTC with `getGmTime`, get the `year` minus the counter variable, and `echo` it.

# Answer
> 1 votes
## Batch, 67 bytes

```
@set/ay=%date:~-4%,z=y-120
@for /l %%i in (%y%,-1,%z%)do @echo %%i

```

# Answer
> 1 votes
# Haskell 125 bytes

The imports take up a large part of the byte count

```
import Data.Time.Clock
import Data.Time.Calendar
main=fmap((\(x,_,_)->[x-120..x]).toGregorian.utctDay)getCurrentTime>>=print

```

# Answer
> 1 votes
# SQLite, 82 80 bytes

```
with b(y)as(select strftime('%Y')union select y-1 from b limit 121)select*from b

```

SQLFiddle

(For ANSI SQL, replace the `strftime()` with `extract(year from current_date)`.)

(2 bytes saved thanks to @MickyT)

# Answer
> 1 votes
# C# - DotNet core - 133 bytes

## Golfed

```
class Program{static void Main(){int x=0,y=System.DateTime.Now.Year;while(x<121){System.Console.Write($"{y-x++}"+(x<121?", ":""));}}}

```

## Ungolfed

```
class Program
{
    static void Main()
    {
        int x=0, y=System.DateTime.Now.Year;

        while(x<121)
        {
            System.Console.Write($"{y-x++}" + (x < 121 ? ", " : ""));
        }
    }
}

```

## Output:

I'm sure this can be improved. I don't particularly like the if statement to display or hide the trailing comma.

# Answer
> 1 votes
## Javascript: ~~68~~ ~~82~~ 59 bytes

`i=121;while(i--){x[i]=Date().substr(11,4)-i;}console.log(x)`

# Answer
> 1 votes
# Ruby, ~~47~~ ~~40~~ 39 bytes

```
p [*0..Time.new.year].last(121).reverse

```

Thanks to @Value Ink for 7 bytes!

Ideone link: https://ideone.com/yRovUl

# Answer
> 1 votes
# Coffeescript, 29 bytes

`->a=Date()[11..14];[a..a-120]`

# Answer
> 1 votes
# Python 3, 54

```
import time
print(*range(time.gmtime()[0],0,-1)[:121])

```

# Answer
> 1 votes
## C#, ~~83~~ 76 bytes

```
n=>{for(n=0;n<121;)System.Console.Write(System.DateTime.Now.Year-n+++" ");};

```

# Answer
> 1 votes
# JavaScript (ES6), ~~66~~ ~~54~~ 51 bytes

My first foray into code golf so I'm open to suggestions for improvements.

The following will output an array of the required years.

```
f=

_=>[...Array(121)].map((x,y)=>Date().split` `[3]-y)

console.log(f());
```

---

## History

### 54 bytes

```
_=>Array(121).fill(Date().split` `[3]).map((x,y)=>x-y)

```

### 66 bytes

```
(y=[Date().split` `[3]],x=121)=>{while(x--)y[x]=(y[0]-x);return y}

```

# Answer
> 1 votes
# Vyxal, ~~11~~ 9 bytes

```
kðt:122-r

```

Try it Online!

-2 thx to @lyxal

# Answer
> 1 votes
# K (ngn/k), 12 bytes (Non-competitive)

```
{x,x-1+!120}

```

Try it online!

K lacks any date-related functions, so this one is non-competitive.

Explanations:

```
{x,x-1+!120}  Main function. Takes x as input
       !120   Generate a range from 0 to 120 (exclusive)
     1+       +1 to each number (1..120)
   x-         x subtract to each number (x-1..x-120)
 x,           Concat x itself as the first number of the array (x,x-1..x-120)

```

# Answer
> 1 votes
# Julia 1.0, ~~46~~ 45 bytes

```
using Dates
y=year(now())
show([y:-1:y-120;])

```

Try it online!

* -1 byte thanks to @amelies: replace `print` with `show`

# Answer
> 1 votes
# Thunno 2, 6 bytes

```
kOṇÞL-

```

Attempt This Online!

#### Explanation

```
kOṇÞL-  # Full program
kO      # Push the current year
  ṇÞ    # Compressed integer 121
    L   # Lowered range
     -  # Subtract
        # Implicit output

```

# Answer
> 0 votes
# Java ~~75~~ 74 bytes

```
public void possible(){
  for(int i=0;i<120;){
    System.out.println(new Date().getYear()-i++);
  }
}

```

Golfed :

```
void p(){for(int i=0;i<120;)System.out.println(new Date().getYear()-i++);}

```

1 byte off. Thanks to @LeakyNun

# Answer
> 0 votes
## Python 2, 113 bytes

```
import datetime
theYear = datetime.datetime.now()
for i in range(theYear.year, theYear.year-121, -1):
   print i,','

```

# Answer
> 0 votes
## QBIC, 33 bytes

```
A=right$(_D,4)┘[!A!,!A!-120,-1|?a

```

# Answer
> 0 votes
# TI-Basic, ~~22~~ 19 bytes

```
max(getDate:seq(I,I,Ans,Ans-120,~1

```

# Answer
> 0 votes
# Groovy, 57 bytes

```
d=new Date().getYear()+1899;(d..d-120).each{println it}

```

**Explanation**

```
d=new Date().getYear()                               //returns how many years have passed since 1900
                      +1899;                         //adding 1900 will give us the current year, but we want the program to start one year before, so we do +1900-1=1899
                            (d..d-120)               //a range from the current year -1 to 120 years before that
                                      .each{print it}// for each element in the range, print it.

```

**Output**

```
2016
2015
2014
...
1898
1897
1896

```

Because of the 1899 trick, it starts with 2016 instead of 2017

Tested on the Groovy Web Console

# Answer
> 0 votes
## VBA 49 bytes

```
a=year(now):for i=a to a-120 step-1:msgbox i:next

```

# Answer
> 0 votes
## JavaScript, 75 71 bytes

Saved 4 bytes thanks to Zachary.

```
e="";for(y=(new Date).getFullYear(),i=y;i>=y-120;i--)e+=i+" ";alert(e)

```

Prints all years into a single alert.

I'm sure it could be improved.

## History

**75 bytes**

```
var e="";for(y=(new Date).getFullYear(),i=y;i>=y-120;i--)e+=i+" ";alert(e);

```

---

(Every year was in a separate alert)

```
for(y=(new Date).getFullYear(),i=y;i>=y-120;i--)alert(i);

```

# Answer
> 0 votes
# Tcl, 76 bytes

```
set y [clock format [clock seconds] -format %Y]
time {puts $y;incr y -1} 121

```

Try it online!

# Answer
> 0 votes
# VBA, 31 Bytes

Anonymous VBE immediate window function that takes no input and outputs to the VBE immediate window

```
For i=0To 120:?Year(Now)-i:Next

```

# Answer
> 0 votes
# Factor, 30 bytes

```
[ now year>> dup 120 - [a,b] ]

```

Try it online!

```
now     ! T{ timestamp { year 2022 } { month 10 } ... etc }
year>>  ! 2022
dup     ! 2022 2022
120     ! 2022 2022 120
-       ! 2022 1902
[a,b]   ! { 2022 2021 2020 ... 1902 }

```

# Answer
> 0 votes
# jq -n, 24 bytes

```
now|gmtime[0]-range(121)

```

Try it online!

# Answer
> 0 votes
# Arturo, 24 bytes

```
$=>[y:now\year y..y-120]

```

Try it!

```
$=>[           ; a function
    y:now\year ; assign current year to y
    y..y-120   ; the range y down to y-120
]              ; end function

```

# Answer
> 0 votes
# Lua, 40 bytes

```
for i=0,120 do print(~~os.date"%Y"-i)end

```

Try it online!

The `~~` is used to remove a trailing `.0` from each year.

# Answer
> -1 votes
### Ruby, 39 36 bytes

```
t=Time.new.year;t.downto(t-120).to_a

```

Old:

```
t=Time.new.year;(t-120..t).to_a.reverse

```

Should be obvious.

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


title: Difference of the square of the sum

text:
# Question
Title: Difference of the square of the sum
**Find the difference between the square of the sums and sum of the squares.**

This is the mathematical representation:

\\$\left(\sum n\right)^2-\sum n^2\\$

Your program/method should take two inputs, these are your lower and upper limits of the range, and are inclusive. Limits will be whole integers above 0.

Your program/method should return the answer.

You may use whichever base you would like to, but please state in your answer which base you have used.

Test case (Base 10)

```
5,9      970
91,123   12087152
1,10     2640

```

This is usual code-golf, so the shorter the answer the better.

# Answer
> 24 votes
# Python 2, 43 bytes

```
f=lambda a,b,s=0:b/a and 2*a*s+f(a+1,b,s+a)

```

Test it on Ideone.

### How it works

Call the function defined in the specification \\$g(a, b)\\$. We have that

$$ \newcommand{\sumab}\[2\]{\sum\_{a \le #1 \le b} #2 \\:} \begin{align} g(a,b) & = \left( \sumab n n \right)^2 - \sumab n {n^2} \\ & = \sumab {i,j} {ij} - \sumab n {n^2} \\ & = \sumab {i\<j} {ij} + \sumab {i=j} {ij} + \sumab {j\<i} {ij} - \sumab n {n^2} \\ & = 2 \sumab {j\<i} {ij} \\ & = 2 \sumab {i} {\sum\_{a \le i \< j} ij} \\ & = \sumab {i} {\left( 2i \sum\_{a \le j \< i} j \right)} \end{align} $$

Define the function \\$f(x, y, s)\\$ recursively as follows.

$$ f(x, y, s) = \begin{cases} 2xs + f(x+1, y, s+x) & \text{ if } x \le y \\ 0 & \text{ if} x \> y \end{cases} $$

By applying the recurrence relation of \\$f(a, b, 0)\\$ a total of \\$b - a\\$ times, we can show that:

$$ \begin{align} f(a, b, 0) & = 2\cdot0 + f(a+1, b, a) \\ & = 2\cdot0 + 2\cdot(a+1)\cdot a + f(a+2, b, a+(a+1)) \\ & = 2\cdot0 + 2\cdot(a+1)\cdot a + 2\cdot(a+2)\cdot(a+(a+1)) + f(a+3, b, a+(a+1)+(a+2)) \\ & \vdots \\ & = \sumab {i} {\left( 2i \sum\_{a \le j \< i} j \right)} + f\left(b+1, b, \sumab j j\right) \\ & = \sumab {i} {\left( 2i \sum\_{a \le j \< i} j \right)} \\ & = g(a, b) \end{align} $$

This is the function **f** of the implementation. While `b/a` returns a non-zero integer, the code following `and` is executed, thus implementing the recursive definition of **f**.

Once `b/a` reaches **0**, we have that **b \> a** and the lambda returns **False = 0**, thus implementing the base case of the definition of **f**.

# Answer
> 15 votes
# MATL, 9 bytes

```
&:&*XRssE

```

**Try it online!**

### Explanation

```
&:   % Inclusive range between the two implicit inputs
&*   % Matrix of all pair-wise products
XR   % Upper triangular part of matrix, without the diagonal
ss   % Sum of all elements of the matrix
E    % Multiply by 2. Implicit display

```

### Example

These are the partial results of each line for inputs `5` and `9`:

1. `&:`

```
5 6 7 8 9

```
2. `&:&*`

```
25 30 35 40 45
30 36 42 48 54
35 42 49 56 63
40 48 56 64 72
45 54 63 72 81

```
3. `&:&*XR`

```
0 30 35 40 45
0  0 42 48 54
0  0  0 56 63
0  0  0  0 72
0  0  0  0  0

```
4. `&:&*XRss`

```
485

```
5. `&:&*XRssE`

```
970

```

# Answer
> 10 votes
## Jelly, ~~9~~ 8 bytes

```
rµS²_²S$

```

Try it online!

```
r         inclusive range from first input to second input
 µ        pass the range to a new monadic chain
  S       the sum
   ²      squared
    _     minus...
     ²S$  the squares summed

```

Thanks to FryAmTheEggman for a byte!

# Answer
> 10 votes
## Python 2, 45 bytes

```
lambda a,b:(a+~b)*(a-b)*(3*(a+b)**2+a-b-2)/12

```

Closed form solution - not the shortest, but I thought it'd be worth posting anyway.

## Explanation

Let `p(n)` be the *n*th square pyramidal number, and `t(n)` be the *n*th triangular number. Then, for *n* over the range *a*, ..., *b*:

* ∑n = `t(b)-t(a-1)`, and
* ∑n² = `p(b) - p(a-1)`
* So (∑n)²-∑n² = `(t(b)-t(a-1))² - (p(b) - p(a-1))`.

This expression reduces to that in the code.

# Answer
> 6 votes
## 05AB1E, 8 bytes

```
ŸDOnsnO-

```

**Explained**

```
ŸD       # range from a to b, duplicate
  On     # sum and square first range
    s    # swap top 2 elements
     nO  # square and sum 2nd range
       - # take difference

```

Try it online

# Answer
> 6 votes
## Mathematica, 21 bytes

```
Tr[x=Range@##]^2-x.x&

```

An unnamed function taking two arguments and returning the difference. Usage:

```
Tr[x=Range@##]^2-x.x&[91, 123]
(* 12087152 *)

```

There's three small (and fairly standard) golfing tricks here:

* `##` represents both arguments at once, so that we can use prefix notation for `Range`. `Range@##` is shorthand for `Range[##]` which expands to `Range[a, b]` and gives us an inclusive range as required.
* `Tr` is for *trace* but using it on a vector simply sums that vector, saving three bytes over `Total`.
* `x.x` is a dot product, saving four bytes over `Tr[x^2]`.

# Answer
> 5 votes
## Labyrinth, ~~28~~ 24 bytes

```
?:?:}+=-:(:(#{:**+**#2/!

```

Try it online!

### Explanation

Since loops tend to be expensive in Labyrinth, I figured the explicit formula should be shortest, as it can be expressed as linear code.

```
Cmd Explanation                 Stacks [ Main | Aux ]
?   Read M.                     [ M | ]
:   Duplicate.                  [ M M | ]
?   Read N.                     [ M M N | ]
:   Duplicate.                  [ M M N N | ]
}   Move copy to aux.           [ M M N | N ]
+   Add.                        [ M (M+N) | N ]
=   Swap tops of stacks.        [ M N | (M+N) ]
-   Subtract.                   [ (M-N) | (M+N) ]
:   Duplicate.                  [ (M-N) (M-N) | (M+N) ]
(   Decrement.                  [ (M-N) (M-N-1) | (M+N) ]
:   Duplicate.                  [ (M-N) (M-N-1) (M-N-1) | (M+N) ]
(   Decrement.                  [ (M-N) (M-N-1) (M-N-2) | (M+N) ]
#   Push stack depth.           [ (M-N) (M-N-1) (M-N-2) 3 | (M+N) ]
{   Pull (M+N) over from aux.   [ (M-N) (M-N-1) (M-N-2) 3 (M+N) | ]
:   Duplicate.                  [ (M-N) (M-N-1) (M-N-2) 3 (M+N) (M+N) | ]
*   Multiply.                   [ (M-N) (M-N-1) (M-N-2) 3 ((M+N)^2) | ]
*   Multiply.                   [ (M-N) (M-N-1) (M-N-2) (3*(M+N)^2) | ]
+   Add.                        [ (M-N) (M-N-1) (3*(M+N)^2 + M - N - 2) | ]
*   Multiply.                   [ (M-N) ((M-N-1)*(3*(M+N)^2 + M - N - 2)) | ]
*   Multiply.                   [ ((M-N)*(M-N-1)*(3*(M+N)^2 + M - N - 2)) | ]
#   Push stack depth.           [ ((M-N)*(M-N-1)*(3*(M+N)^2 + M - N - 2)) 1 | ]
2   Multiply by 10, add 2.      [ ((M-N)*(M-N-1)*(3*(M+N)^2 + M - N - 2)) 12 | ]
/   Divide.                     [ ((M-N)*(M-N-1)*(3*(M+N)^2 + M - N - 2)/12) | ]
!   Print.                      [ | ]

```

The instruction pointer then hits a dead end and has to turn around. When it now encounters `/` it attempts a division by zero (since the bottom of the stack is implicitly filled with zeros), which terminates the program.

# Answer
> 4 votes
## Haskell, 34 bytes

```
a#b=sum[a..b]^2-sum(map(^2)[a..b])

```

Usage example: `91 # 123` -\> `12087152`.

Nothing to explain.

# Answer
> 3 votes
# Brachylog, 24 bytes

```
:efL:{:2^.}a+S,L+:2^:S-.

```

Expects the 2 numbers in Input as a list, e.g. `[91:123]`.

### Explanation

```
:efL                     Find the list L of all integers in the range given in Input
    :{:2^.}a             Apply squaring to each element of that list
            +S,          Unify S with the sum of the elements of that list
               L+:2^     Sum the elements of L, then square the result
                    :S-. Unify the Output with that number minus S

```

# Answer
> 3 votes
# Perl 6,  ~~36 32~~  31 bytes

```
~~{([+] $_=@_[0]..@_[1])²-[+] $_»²}
{([+] $_=$^a..$^b)²-[+] $_»²}~~
{[+]($_=$^a..$^b)²-[+] $_»²}

```

Test it

### Explanation:

```
{ # bare block with placeholder parameters $a and $b

  [+](# reduce with &infix:<+>
      # create a range, and store it in $_
      $_ = $^a .. $^b
  )²
  -
  [+] # reduce with &infix:<+>
    # square each element of $_ ( possibly in parallel )
    $_»²
}

```

### Test:

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

my @tests = (
  (5,9) => 970,
  (91,123) => 12087152,
  (1,10) => 2640,
);

plan +@tests;

my &diff-sq-of-sum = {[+]($_=$^a..$^b)²-[+] $_»²}

for @tests -> $_ ( :key(@input), :value($expected) ) {
  is diff-sq-of-sum(|@input), $expected, .gist
}

```

```
1..3
ok 1 - (5 9) => 970
ok 2 - (91 123) => 12087152
ok 3 - (1 10) => 2640

```

# Answer
> 3 votes
## Matlab, ~~30~~ ~~29~~ 28 bytes

Using Suever's idea of `norm` gives us 2 bytes less

```
@(x,y)sum(x:y)^2-norm(x:y)^2

```

Old (simple) version:

```
@(x,y)sum(x:y)^2-sum((x:y).^2)

```

# Answer
> 3 votes
# Octave, ~~27~~ 23 bytes

```
@(x,y)sum(z=x:y)^2-z*z'

```

Creates an anonymous function named `ans` which accepts two inputs: `ans(lower, upper)`

**Online Demo**

**Explanation**

Creates a row vector from `x` to `y` (inclusive) and stores it in `z`. We then sum all the elements using `sum` and square it (`^2`). To compute the sum of the squares, we perform matrix multplication between the row-vector and it's transpose. This will effectively square each element and sum up the result. We then subtract the two.

# Answer
> 3 votes
## JavaScript (ES6), ~~50~~ 37 bytes

```
f=(n,m,s=0)=>n>m?0:2*n*s+f(n+1,m,n+s)

```

Now a port of @Dennis♦'s Python solution.

# Answer
> 3 votes
## Haskell, 36 bytes

```
m#n=sum[2*i*j|i<-[m..n],j<-[i+1..n]]

```

---

```
λ> m # n = sum [ 2*i*j | i <- [m..n], j <- [i+1..n] ]
λ> 5 # 9
970
λ> 91 # 123
12087152
λ> 1 # 10
2640

```

Note that

$$\left( \sum\_{k=m}^n k \right)^2 - \sum\_{k=m}^n k^2 = \cdots = \sum\_{k\_1=m}^n \sum\_{k\_2=m\\ k\_2 \neq k\_1}^n k\_1 k\_2 = \sum\_{k\_1=m}^n \sum\_{k\_2=k\_1+1}^n 2 \\,k\_1 k\_2$$

# Answer
> 3 votes
# Java, ~~84~~ 77 characters, ~~84~~ 77 bytes

7 bytes smaller due to Martin Ender and FryAmTheEggMan, thank you.

`public int a(int b,int c){int e=0,f=0;for(;b<=c;e+=b,f+=b*b++);return e*e-f;}`

Using the three test cases in the original post: http://ideone.com/q9MZSZ

Ungolfed:

```
public int g(int b, int c) {
    int e = 0, f = 0;
    for (; b <= c; e += b, f += b * b++);
    return e*e-f;
}

```

Process is fairly self-explanatory. I declared two variables to represent the square of the sums and the sum of the squares and repeatedly incremented them appropiately. Finally, I return the computed difference.

# Answer
> 3 votes
# JavaScript (ES6), 46 bytes

```
f=(x,y,s=0,p=0)=>x<=y?f(x+1,y,s+x,p+x*x):s*s-p

```

# Answer
> 3 votes
# Factor, 48 bytes

```
[ [a,b] [ [ sq ] map sum ] [ sum sq ] bi - abs ]

```

An anonymous function.

```
[
  [a,b] ! a range from a to b
  [
    [ sq ] map sum ! anonymous function: map sq over the range and sum the result
  ]
  [ sum sq ] ! the same thing, in reverse order
  bi - abs   ! apply both anon funcs to the range, subtract them and abs the result
]

```

# Answer
> 3 votes
# Aheui (esotope), 108 bytes(36 chars)

```
방빠방빠쌍다쌍상싸사타빠밤타빠받다파반다받상싸사빠따따다따따받밤따나망히

```

Try it online!

---

Takes two inputs from user(separated by line feed or whitespace) and print result of following function;

> \\$f(a,b)=((a-b)\cdot(a-b-1)\cdot(3\cdot(a+b)^2+a-b-2))/12\\$

# Answer
> 2 votes
# APL, ~~23~~ 20 bytes

```
-/+/¨2*⍨{(+/⍵)⍵}⎕..⎕

```

Works in NARS2000.

# Answer
> 2 votes
# MATL, 11 bytes

```
&:ts2^w2^s-

```

Try it online!

Explanation:

```
&:           #Create a range from the input
  t          #Duplicate it
   s2^       #Sum it and square it
      w      #swap the two ranges
       2^s   #Square it and sum it
          -  #Take the difference

```

# Answer
> 2 votes
## PowerShell v2+, 47 bytes

Two variations

```
param($n,$m)$n..$m|%{$o+=$_;$p+=$_*$_};$o*$o-$p

$args-join'..'|iex|%{$o+=$_;$p+=$_*$_};$o*$o-$p

```

In both cases we're generating a range with the `..` operator, piping that to a loop `|%{...}`. Each iteration, we're accumulating `$o` and `$p` as either the sum or the sum-of-squares. We then calculate the square-of-sums with `$o*$o` and subtract `$p`. Output is left on the pipeline and printing is implicit.

# Answer
> 2 votes
# Pyth, 11 bytes

```
s*M-F#^}FQ2

```

Try it online!

```
s*M-F#^}FQ2
       }FQ    Compute the range
      ^   2   Generate all pairs
   -F#        Remove those pairs who have identical elements
 *M           Product of all pairs
s             Sum.

```

# Answer
> 2 votes
# Japt, 10 bytes

```
õV
x²aUx ²

```

Try it

# Answer
> 2 votes
# Jelly, 6 bytes

```
rµÄḋḊḤ

```

Recent improvements to the Jelly language allow a compact implementation of the \\$g\\$ function from my Python answer.

Try it online!

### How it works

```
rµÄḋḊḤ  Main link. Arguments: a, b (integers)

r       Range; yield R := [a, ..., b].
 µ      Begin a monadic chain with argument R.
  Ä     Accumulate; take the cumulative sum of R.
    Ḋ   Deque; yield [a+1, ..., b].
   ḋ    Take the dot product, ignoring the last term of the cumulative sum.
     Ḥ  Unhalve; double the result.

```

# Answer
> 2 votes
# Vyxal, 8 bytes

```
ṡ:²∑$∑²ε

```

Try it Online!

## How?

```
ṡ:²∑$∑²ε
ṡ        # Inclusive range between (implicit) second input and (implicit) first input
 :       # Duplicate this range
  ²      # Square each of the duplicate
   ∑     # Summate
    $    # Swap so the other range is at the top
     ∑   # Summate
      ²  # Then square
       ε # Absolute difference between the two

```

# Answer
> 2 votes
# Thunno 2, 8 bytes

```
IDS²s²S-

```

Attempt This Online!

#### Explanation

```
IDS²s²S-  # Implicit input
ID        # Inclusive range; duplicate
  S²      # Sum the list; square the sum
    s     # Swap so the range is back on top
     ²S   # Square each item; sum the list
       -  # Take the difference
          # Implicit output

```

# Answer
> 1 votes
## CJam, 17 bytes

```
q~),>_:+2#\2f#:+-

```

Test it here.

### Explanation

```
q~       e# Read and evaluate input, dumping M and N on the stack.
),       e# Increment, create range [0 1 ... N].
>        e# Discard first M elements, yielding [M M+1 ... N].
_        e# Duplicate.
:+2#     e# Sum and square.
\2f#:+   e# Swap with other copy. Square and sum.
-        e# Subtract.

```

Alternatively, one can just sum the products of all distinct pairs (basically multiplying out the square of the sum, and removing squares), but that's a byte longer:

```
q~),>2m*{)-},::*:+

```

# Answer
> 1 votes
# JavaScript (ES6), 67 bytes

```
a=>b=>([s=q=0,...Array(b-a)].map((_,i)=>q+=(s+=(n=i+a),n*n)),s*s-q)

```

## Test Suite

```
f=a=>b=>([s=q=0,...Array(b-a)].map((_,i)=>q+=(s+=(n=i+a),n*n)),s*s-q)
e=s=>`${s} => ${eval(s[0])}` // template tag format for tests
console.log(e`f(5)(9)`)
console.log(e`f(91)(123)`)
console.log(e`f(1)(10)`)
```

# Answer
> 1 votes
# J, 29 bytes

Port of Doorknob's Jelly answer.

```
[:(+/@(^&2)-~2^~+/)[}.[:i.1+]

```

## Usage

```
>> f = [:(+/@(^&2)-~2^~+/)[}.[:i.1+]
>> 91 f 123x
<< 12087152

```

Where `>>` is STDIN, `<<` is STDOUT, and `x` is for extended precision.

# Answer
> 1 votes
## Pyke, 11 bytes

```
h1:Ds]MXXs-

```

Try it here!

```
h1:         - inclusive_range(input)
   Ds]      -     [^, sum(^)]
      MX    -    deep_map(^, <--**2)
         s  -   ^[1] = sum(^[1])
          - -  ^[0]-^[1]

```

# Answer
> 1 votes
# Julia, 25 bytes

```
f(a,b,x=a:b)=sum(x)^2-x'x

```

This is a function that accepts two integers and returns a 1x1 integer array.

The approach is simple: Construct a `UnitRange` from the endpoints `a` and `b` and call it `x`, then sum `x`, square it, and subtract its norm, which is computed as `transpose(x) * x`.

Try it online! (includes all test cases)

# Answer
> 1 votes
# TI-BASIC, 19 bytes

```
Prompt N,M
randIntNoRep(N,M
sum(Ans)<sup>2</sup>-sum(Ans<sup>2</sup>

```

`randIntNoRep` gets the range (shuffled). The rest is pretty self explanatory.

# Answer
> 1 votes
# Fith, 52 bytes

```
{ 1 + range dup sum 2 pow swap { 2 pow } map sum - }

```

This is an anonymous function that takes the two numbers on the stack and leaves a single number.

Explanation:

```
{
    1 + range dup      2 ranges from a to b inclusive
    sum 2 pow          Sum one and square it
    swap               Bring a fresh range to the top
    { 2 pow } map sum  Square every element and sum the list
    -                  Subtract
}

```

# Answer
> 1 votes
# GeoGebra, 91 bytes

```
a(x)=(x²+x)/2
b(x)=x³/3+x²/2+x/6
c(x,y)=(a(y)-a(x))²
d(x,y)=b(y)-b(x)
c(x-1,y)-d(x-1,y)

```

Defines a function (probably `e(x,y)`) that computes the desired difference.
`a(x)` calculates the sum of natural numbers between `0` and `x`.
`b(x)` calculates the sum of the squares of the natural numbers between `0` and `x`.
`c(x,y)` first computes the sum of the natural numbers between `x` and `y`, then squares that sum.
`d(x,y)` calculates the sum of squares between `b(x)` and `b(y)`.
The last line defines a multi-variable function that finishes the calculation. The function is automatically assigned a name, saving a few bytes.

# Answer
> 1 votes
## R - 33 bytes

```
x=scan():scan();sum(x)^2-sum(x^2)

```

pass your lower limit to the first `scan` then your upper limit to the second `scan`

# Answer
> 1 votes
# Whispers v2, 90 bytes

```
> Input
> Input
> 2
>> 1…2
>> L*3
>> Each 5 4
>> ∑6
>> ∑4
>> 8*3
>> 9-7
>> Output 10

```

Try it online!

# Answer
> 1 votes
# Julia 0.6, 21 bytes

```
r->sum(r)^2-sum(r.^2)

```

Returns an anonymous function that takes a `Range`, eg `f(1:10)`, which then returns the result.

Try it online!

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

```
f(n,m){double a,b;for(;n<=m;a+=n,b+=pow(n++,2));return pow(a,2)-b;}

```

Try it online!

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

```
a,b;f(n,m){for(a=b=0;m/n;a+=n++)b+=n*n;n=a*a-b;}

```

Try it online!

# Answer
> 1 votes
# Red, 70 bytes

```
func[a b][s: t: 0 until[s: s + a t: a * a + t  b < a: a + 1]s * s - t]

```

Try it online!

# Answer
> 1 votes
## Excel, 60 bytes

```
=(B1^2+B1-A1^2+A1)^2/4-(2*B1^3+3*B1^2+B1-2*A1^3+3*A1^2-A1)/6

```

Algebraic reshuffling of more verbose implementation: For inputs `a` and `b`:

```
(B1*(B1+1)-A1*(A1-1))/2          // (Sum of b) - (Sum of a-1)
(  )^2                           //  squared
B1*(B1+1)*(2*B1+1)/6             //  Sum of (b squared)
A1*(A1-1)*(2*A1-1)/6             //  Sum of (a-1 squared)

```

# Answer
> 1 votes
# C# (.NET Core), 62 bytes

```
(a,b)=>{int x=0,y=0;for(;a<=b;a++){x+=a;y+=a*a;}return x*x-y;}

```

Try it online!

Ungolfed:

```
(a, b) => {                 // takes in two integer inputs, delimited by a comma
    int x = 0, y = 0;       // initializes x and y
    for(; a <= b; a++)      // increment a until a equals b
    {
        x += a;             // add current a to x
        y += a * a;         // add square of current a to y
    }
    return (x * x) - y;     // return the difference of the square of the sums (x*x) and the sum of the squares (y)
}

```

# Answer
> 1 votes
# Python 3, ~~66~~ 65 bytes

```
lambda a,b:sum(x*y*2for x in range(a,b+1)for y in range(x+1,b+1))

```

Try it online!

with @Dennis formulae and w/o recursion, yet another Python solution (as I cannot comment @leaky-nun solution (not enough reputation)

# Answer
> 1 votes
# PHP, 58 bytes

```
for([,$p,$q]=$argv;$p<=$q;$s+=$p++)$t+=$p*$p;echo$s*$s-$t;

```

Run with `-nr` or try it online.

# Answer
> 1 votes
# Sidef, ~~46~~ 44 bytes

> Translation of: my Factor solution

```
{|a,b|R=a..b;R.map{.sqr}.sum-R.sum.sqr->abs}

```

Try it online!

use it like `x.run(4, 20)` -\> 38760

Previous

```
->(a,b,R=a..b){R.map{.sqr}.sum-R.sum.sqr->abs}

```

longer, explained

```
->                       # the next list is a function parameter list
(a, b, R = a .. b )      # R is a RangeNum over the a and b
{                        # a Block
  return                 # return the whole expression
  R.map{ |n|             # map this Block over the range
    return n.sqr         # squared value
  }.sum                  # summed the range
  -                      # subtract
  R.sum.sqr              # sum of the range, squared
  ->abs                  # call Number.abs on everything on the left-hand side of ->
}                        # ok, we're done

```

# Answer
> 1 votes
# Tcl, 76 ~~80~~ bytes

```
proc S l\ u {while \$l<=$u {incr Q $l
append R -$l*$l
incr l}
expr $Q**2+$R}

```

Try it online!

# Answer
> 1 votes
## Burlesque - 16 bytes

```
r@J++2?^j)S[++?-

r@                  range
  J                 dup
   ++               sum
     2?^            square it
        j           swap
         )S[        map (square)
            ++      sum
              ?-    subtract

```

**Alternate versions:**

```
r@JJ?*++j++S[?-ab
r@J++2?^jqS[ms?-
r@J++J?*jqS[ms?-
r@J++J?*jJ?*++?-
r@J)S[++j++S[j?-

```

^- and this is the art of golfing :(.

# Answer
> 1 votes
# Rust, 67 bytes

```
|b,e|{let mut t=0;let mut s=0;for i in b..=e{t+=i;s+=i*i;}(t*t)-s};

```

A closure that takes two integers and returns an integer.

# Answer
> 1 votes
# Pony, 73 bytes

```
fun f(m:U64,n:U64,s:U64=0):U64=>if m>n then 0 else(2*m*s)+f(m+1,n,m+s)end

```

sort of ungolfed

```
  fun apply(m: U64, n: U64, s: U64 = 0): U64 =>
    if m > n then 0
    else (2 * m * s) + apply(m + 1, n, m + s) end

```

Port of Neil's JavaScript solution.

# Answer
> 1 votes
# K (oK), 24 bytes

```
{(t*t:+/s)-+/s*s:x_!1+y}

```

Try it online!

"Boring" but straightforward.

# Answer
> 1 votes
# Arturo, ~~42~~ 35 bytes

```
$=>[-*<=∑r∑map r:<=&..&'z->z*z]

```

Try it

# Answer
> 1 votes
# JavaScript, 49 bytes

Without recursion:

```
(b,e)=>eval('for(x=y=0;b<=e;y+=b*b++)x+=b;x*x-y')

```

Try it:

```
f=(b,e)=>eval('for(x=y=0;b<=e;y+=b*b++)x+=b;x*x-y')

console.log(f(5,9)); // 970
console.log(f(91,123)); // 12087152
console.log(f(1,10)); // 2640
```

# Answer
> 1 votes
# Pyt, 8 bytes

```
ŘĐĐƩ²↔·-

```

Try it online!

Takes two inputs on separate lines as `max`, `min`

```
Ř               implicit inputs; Řange
 ĐĐ             Đuplicate array on stack twice
   Ʃ²           Get square of sum
     ⇹·         Get sum of squares
       -        Subtract; implicit print

```

# Answer
> 1 votes
# Ly, 22 bytes

```
nnR&s&+:*>l[:*sp<l->]<

```

Try it online!

This is a straight forward interpretation of the rules...

```
nnR                     - get the start/end, generate the sequence of numbers
   &s                   - save the sequence...
     &+                 - sum it
       :*               - square the sum
         >l             - load the sequence on a new stack
           [        ]   - while the stack isn't empty
            :*          - square the number
              sp<l      - move the squared number to the other stack
                  ->    - subtract and go back to the second stack
                     <  - switch back to the accumulator stack
                        - the number on the stack prints automatically on exit

```

# Answer
> 1 votes
# J-uby, 33 bytes

```
:!~|:-%[:sum|g= ~:**&2,:*&g|:sum]

```

(The space between `=` and `~` is necessary to keep the Ruby lexer from interpreting them as the `=~` operator.)

## Explanation

```
:!~ | :- % [:sum | g = ~:** & 2, :* & g | :sum]

:!~ |                                            # Range, then
      :- % [                   ,              ]  # difference of...
            :sum | g = ~:** & 2                  #   sum, then square (save the square function in g), and
                                 :* & g | :sum   #   map with square, then sum

```

Attempt This Online!

# Answer
> 0 votes
# Python, 62 bytes

```
lambda a,b:sum(range(a,b+1))**2-sum(x*x for x in range(a,b+1))

```

Or, longer:

```
lambda a,b:sum(sum(x*y for y in range(a,b+1)if x-y)for x in range(a,b+1))

```

Ideone both!

# Answer
> 0 votes
# Java, 95 bytes

```
public int d(int a,int b){int i=a,j,s=0;for(;i<=b;i++)for(j=a;j<=b;j++)s+=i==j?0:i*j;return s;}

```

Ideone it!

# Answer
> 0 votes
# Actually, 11 bytes

```
u@x;♂²Σ@Σ²-

```

Try it online!

# Answer
> 0 votes
# R, 23 bytes

```
sum(i:j)^2-sum((i:j)^2)

```

Does pretty much what you expect by taking i and j as inputs.

# Answer
> 0 votes
## Actually, 10 bytes

```
u@x;;*@Σ²-

```

Try it online!

Explanation:

```
u@x;;*@Σ²-
u@x         range(a, b+1)
   ;;       two copies
     *      dot product with itself (equal to sum of squares)
      @Σ²   sum remaining copy, square sum
         -  subtract

```

# Answer
> 0 votes
## Perl 5.10, 41 bytes

```
map{$s+=$_,$r+=$_**2}(<>..<>);say$s**2-$r

```

Input is given on 2 lines, for instance:

```
61
127

```

Try it here!

# Answer
> 0 votes
# CoffeeScript, 49 Bytes

`f=(n,m,s=0)->if n>m then 0else 2*n*s+f(n+1,m,n+s)`

Translation of Neil's answer

Output:

`f 91, 123 == 12087152
 => true`

# Answer
> 0 votes
# Python 2.7, 82 bytes 85 bytes

```
def a(l, u):
    c=0
    d=0
    for e in range(l, u+1):
        c+=e
        d+=e**2
    return c**2-d

```

Works in base 10.

# Answer
> 0 votes
# Julia 0.6, 21 bytes

```
r->2triu(r*r',1)|>sum

```

Try it online!

Julia port of Luis Mendo's MATL answer. Comes out to the same bytecount as the other Julia answer by @gggg. Takes a `Range` similar to that answer, does a matrix multiply of it with its transpose to get all pairwise products in a matrix. Takes the upper triangular portion of that (the 1 argument is to denote the distance from the leading diagonal to start from), multiplies that by 2, and finally sums the values and returns that implicitly.

# Answer
> 0 votes
# Wolfram Language (Mathematica), 18 bytes

```
Tr@#^2-#.#&@*Range

```

Try it online!

Composition of `Tr@#^2-#.#&` (square of sum minus sum of squares, where sum of squares is implemented via dot product) and `Range` (list of all integers between the two inputs). If you like seeing the operations in order, `Range/*Tr@#^2-#.#&` is equivalent.

As a bonus, also solves this challenge with no modifications, since `Range` can either take one argument (giving the range from `1` to the input) or two. (But it's not the most efficient solution possible there.)

# Answer
> 0 votes
# Bash, ~~74~~ 65 bytes

```
x=y=0;for i in `seq $1 $2`;{ x=$[x+i];y=$[y+i*i]; };echo $[x*x-y]

```

Try it online!

I'm no expert at bash golfing, but this works.
Managed to cut 9 bytes just by reading through the bash golfing tips thread

# Answer
> 0 votes
# Tcl, 105 bytes

```
proc d a\ b {while {[incr a]<=$b} {set j $a
while \$j<=$b {incr p [expr 2*([incr j]-1)*($a-1)]}}
expr $p}

```

Try it online!

~~\# Tcl, 112 bytes~~

~~```
proc d a\ b {set i [expr $a-1]
while \$i<$b {set j [incr i]
while \$j<$b {incr p [expr 2*[incr j]*$i]}}
expr $p}

```~~

# Answer
> 0 votes
# Factor \+ `math.unicode`, 34 bytes

```
[ [a,b] dup Σ sq swap norm-sq - ]

```

Try it online!

* `[a,b]` Create a range from the input.
* `dup Σ sq swap` Square of sum.
* `norm-sq` Sum of squares.
* `-` Subtract.

---
Tags: code-golf, math, arithmetic, array
---