title: Every word from babab to zyzyz

text:
# Question
Title: Every word from babab to zyzyz
Your task is to write a program that will output a readable list of every five letter words with the structure:

**consonant - vowel - consonant - vowel - consonant**

The output should be sorted alphabetically with one word per line and no words repeated twice. It can be lowercase or uppercase but not mixed. So the list could start and end like this:

```
babab
babac
babad
...
zyzyw
zyzyx
zyzyz

```

Vowels are **a**-**e**-**i**-**o**-**u**-**y**, the other 20 English-alphabet letters are consonants.
Words don't have to be actual dictionary words.
Shortest code wins.

*Note: A few years ago I stumbled upon a program on a university website that did exactly that. Turns out my first and last name fit the c-v-c-v-c constraint, and i'd been googling myself.*

# Answer
> 29 votes
## Mathematica, ~~72~~ ~~65~~ 61 bytes

```
Print@@@Tuples@{a=##/(b=#5#9#15#21#25#)&@@Alphabet[],b,a,b,a}

```

For testing, I recommend replacing `Print@@@` with `""<>#&/@`. Mathematica will then display a truncated form showing the first few and last few words, instead of taking forever to print 288,000 lines.

### Explanation

I finally found a use for dividing strings. :)

I've been intrigued by the possibility of adding or multiplying strings for a while, but the actual use cases are fairly limited. The main point is that something like `"foo"+"bar"` or `"foo"*"bar"` (and consequently, the short form `"foo""bar"`) is completely valid in Mathematica. However, it doesn't really know what to do with the strings in arithmetic expressions, so these things remain unevaluated. Mathematica *does* apply generally applicable simplifications though. In particular, the strings will be sorted into canonical order (which is fairly messed up in Mathematica, once you start sorting strings containing letters of various cases, digits and non-letters), which is often a dealbreaker, but doesn't matter here. Furthermore, `"abc""abc"` will be simplified to `"abc"^2` (which is a problem when you have repeated strings, but we don't have that either), and something like `"abc"/"abc"` will actually cancel (which we'll be even making use of).

So what are we trying to golf here. We need a list of vowels and a list of consonants, so we can feed them to `Tuples` to generate all possible combinations. My first approach was the naive solution:

```
Characters@{a="bcdfghjklmnpqrstvwxz",b="aeiouy",a,b,a}

```

That hardcoded list of consonants does hurt a bit. Mathematica does have an `Alphabet` built-in which would allow me to avoid it, if I were able to remove the vowels in a cheap way. This is where it gets tricky though. The simplest way to remove elements is `Complement`, but that ends up being longer, using one of the following options:

```
{a=Complement[Alphabet[],b=Characters@"aeiouy"],b,a,b,a}
{a=Complement[x=Alphabet[],b=x[[{1,5,9,15,21,25}]]],b,a,b,a}

```

(Note that we don't need to apply `Characters` to the whole thing any more, because `Alphabet[]` gives a list of letters, not a string.)

So let's try that arithmetic business. If we represent the entire alphabet as a product of letters instead of a list, then we can remove letters by simple division, due to the cancelling rule. That saves a lot of bytes because we won't need `Complement`. Furthermore, `"a""e""i""o""u""y"` is actually a byte shorter than `Characters@"aeiouy"`. So we do this with:

```
a=##/(b="a""e""i""o""u""y")&@@Alphabet[]

```

Where we're storing the consonant and vowel products in `a` and `b`, respectively. This works by writing a function which multiplies all its arguments with `##` and divides them by the product of vowels. This function is *applied* to the alphabet list, which passes each letter in as a separate argument.

So far so good, but now we have

```
{a=##/(b="a""e""i""o""u""y")&@@Alphabet[],b,a,b,a}

```

as the argument to `Tuples`, and those things are still products, not lists. Normally, the shortest way to fix that is putting a `List@@@` at the front, which turns the products into lists again. Unfortunately, adding those 7 bytes makes it longer than the naive approach.

However, it turns out that `Tuples` doesn't care about the heads of the inner lists at all. If you do

```
Tuples[{f[1, 2], f[3, 4]}]

```

(Yes, for an undefined `f`.) You'll get:

```
{{1, 3}, {1, 4}, {2, 3}, {2, 4}}

```

Just as if you had used a `List` instead of `f`. So we can actually pass those products straight to `Tuples` and still get the right result. This saves 5 bytes over the naive approach using two hardcoded strings.

Now the `"a""e""i""o""u""y"` is still fairly annoying. But wait, we can save a few bytes here as well! The arguments of our function are the individual letters. So if we just pick out the right arguments, we can reuse those instead of the string literals, which is shorter for three of them. We want arguments `#` (short for `#1`), `#5`, `#9`, `#15`, `#21` and `#25`. If we put `#` at the end, then we also don't need to add any `*` to multiply them together, because (regex) `#\d+` is a complete token that can't have any non-digit appended to it. Hence we end up with `#5#9#15#21#25#`, saving another 4 bytes.

# Answer
> 14 votes
# Perl, 47 bytes

```
#!perl -l
/((^|[aeiouy])[^aeiouy]){3}/&&print for a..1x5

```

Counting the shebang as one.

Try it online!

# Answer
> 12 votes
# Python 3 - 110 bytes

```
a,b="bcdfghjklmnpqrstvwxz","aeiouy";print(*(c+d+e+f+g for c in a for d in b for e in a for f in b for g in a))

```

Straightforward looping fun :)

# Answer
> 10 votes
## Ruby, ~~72 71~~ 52 bytes

```
puts (?z..?z*5).grep /#{["[^aeiouy]"]*3*"[aeiouy]"}/

```

Thanks to Value Ink for the basic idea, which brought that down to 60 bytes.

# Answer
> 8 votes
# 05AB1E, ~~18~~ 16 bytes

**05AB1E** uses CP-1252 encoding.

```
žP3ãžO3ãâ€øJ€¨ê»

```

**Explanation**

```
žP3ã                # push all combinations of 3 consonants
    žO3ã            # push all combinations of 3 vowels
        â           # cartesian product
         €ø         # zip each pair of [ccc,vvv] (c=consonant,v=vowel)
           J        # join to list of strings ['cvcvcv','cvcvcv' ...]
            €¨      # remove last vowel from each
              ê     # sort and remove duplicates
              »     # join on newlines

```

For testing purposes I recommend replacing `žP` with a few consonants and `žO` with a few vowels.

Example using 5 consonants and 3 vowels

# Answer
> 8 votes
# Python 2, ~~120~~ ~~102~~ 94 bytes

```
from itertools import*
lambda:map(''.join,product(*(('AEIOUY','BCDFGHJKLMNPQRSTVWXZ')*3)[1:]))

```

Try it online!

# Answer
> 8 votes
# Pure Bash, 74

```
v={a,e,i,o,u,y}
c={b,c,d,f,g,h,{j..n},{p..t},v,w,x,z}
eval echo $c$v$c$v$c

```

Straightforward brace expansion.

Try it online.

---

If each item must be on its own line, then we have:

# Pure Bash, 84

```
v={a,e,i,o,u,y}
c={b,c,d,f,g,h,{j..n},{p..t},v,w,x,z}
eval printf '%s\\n' $c$v$c$v$c

```

# Answer
> 7 votes
# PHP, ~~88~~ ~~86~~  ~~84~~ 80 bytes

pretty string increment :)
6 bytes saved by @Christoph

```
for($s=$v=aeiouy;++$s<zyzza;preg_match("#[^$v]([$v][^$v]){2}#",$s)&&print"$s
");

```

loops through all strings from `bababa` to `zyzyz` and tests if they match the pattern. Run with `-nr`.

# Answer
> 6 votes
## Haskell, ~~54~~ 51 bytes

```
l="bcdfghjklmnpqrstvwxz":"aeiouy":l
mapM(l!!)[0..4]

```

`mapM func list` builds all words by taking the possible characters for index i from the list returned by `func (list!!i)`.

Edit: @xnor found 2 bytes to save and looking at his solution, I found another one.

# Answer
> 6 votes
# Python 2, 85 bytes

```
W='BCDFGHJKLMNPQRSTVWXZ'
for s in['AEIOUY',W]*2:W=[w+c for w in W for c in s]
print W

```

Try it online!

I'm back six years later with a golf. The string `W` of consonants can also be used as the result of the first loop which gives all first-letter options. The fact that it's a string rather than a list is harmless because we just need to iterate over it. We can then write the other four letter sets cleanly as `['AEIOUY',W]*2`.

# Python, 92 bytes

```
f=lambda i=-4,s='':i*[s]or sum([f(i+1,s+c)for c in i%2*'AEIOUY'or'BCDFGHJKLMNPQRSTVWXZ'],[])

```

Try it online!

Can't let `itertools` win out. Iterative is 1 byte longer in Python 2.

```
W='',
for s in(['AEIOUY','BCDFGHJKLMNPQRSTVWXZ']*3)[1:]:W=[w+c for w in W for c in s]
print W

```

# Answer
> 5 votes
# MATL, 21 bytes

```
11Y2'y'h2Y2X~6Myyy&Z*

```

Try it online! (but output is truncated).

```
11Y2   % Push 'aeiou' (predefined literal)
'y'    % Push 'y'
h      % Concatenate: gives 'aeiouy'
2Y2    % Push 'abcdefghijklmnopqrstuvwxyz' (predefined literal)
X~     % Set symmetric difference: gives 'bcdfghjklmnpqrstvwxz'
6M     % Push 'aeiouy' again
yyy    % Duplicate the second-top element three times onto the top. The stack now
       % contains 'bcdfghjklmnpqrstvwxz', 'aeiouy', 'bcdfghjklmnpqrstvwxz',
       % 'aeiouy', 'bcdfghjklmnpqrstvwxz'
&Z*    % Cartesian product of all arrays present in the stack. Implicity display

```

# Answer
> 5 votes
# JavaScript (ES6), ~~91~~ 90 bytes

```
f=(s='',i=4)=>{for(c of i%2?'aeiouy':'bcdfghjklmnpqrstvwxz')i?f(s+c,i-1):console.log(s+c)}

```

### Edits

* ETHproductions: -1 byte by removing extraneous group around ternary operator in `for` statement

### Explanation

This defines a 5-deep recursive function that uses the parity of its depth of call to determine whether to iterate vowels or consonants. On each iteration, it checks to see whether to recurse or print by checking the amount of recursions left, and concatenates the letter of its current iteration to the end of the 5 character string that is currently being built depth-first.

Alternative 89 byte solution assuming ISO8859-1 encoding:

```
f=(s='',i=4)=>{for(c of i%2?'aeiouy':btoa`mÇ_äiéª»-¿s`)i?f(s+c,i-1):console.log(s+c)}

```

Alternative 96 byte solution that returns entire output as single string:

```
f=(s='',i=4,o='')=>eval("for(c of i%2?'aeiouy':'bcdfghjklmnpqrstvwxz')o+=i?f(s+c,i-1):s+c+`\n`")

```

**Run at your own risk.** For the 91 byte solution, just use `f()` and for the 97 byte alternative, use `console.log(f())`.

# Answer
> 5 votes
# Brachylog, 18 bytes

```
@W:@Dg:2jcb:eac@w\

```

Try it online!

### Explanation

```
@W:@D                 The list ["aeiouy", "bcdfghjklmnpqrstvwxz"]
     g:2jcb           The list ["bcdfghjklmnpqrstvwxz", "aeiouy", "bcdfghjklmnpqrstvwxz", "aeiouy", "bcdfghjklmnpqrstvwxz"]
           :ea        Take one character of each string
              c       Concatenate into a single string
               @w     Write to STDOUT followed by a newline
                 \    Backtrack: try other characters of the string

```

# Answer
> 5 votes
## C, ~~201~~ ~~199~~ ~~186~~ ~~184~~ ~~183~~ ~~169~~ 163 bytes

Doing it a bit differently than with the previous basic counting method:

```
f(){for(char*c="bcdfghjklmnpqrstvwxz",*v="aeiouy",i[5]={0},*s[]={c,v,c,v,c},j=0;j<5;puts("")){for(j=5;j--;putchar(s[j][i[j]]));for(;j++<5&&!s[j][++i[j]];i[j]=0);}}

```

Ungolfed:

```
f() {
    for(char *c="bcdfghjklmnpqrstvwxz", *v="aeiouy", i[5]={0}, *s[]={c,v,c,v,c}, j=0; j<5; puts("")) {
        for (j=5; j--; putchar(s[j][i[j]])) ;
        for (; j++ < 5 && !s[j][++i[j]]; i[j]=0) ;
    }
}

```

And written in a bit more conventional way:

```
f() {
    char *c="bcdfghjklmnpqrstvwxz", *v="aeiouy", i[]={0,0,0,0,0}, *s[]={c,v,c,v,c}, j=0;
    while (j>=0) {
        for (j=0; j<5; j++) putchar(s[j][i[j]]); // output the word
        while (--j>=0 && !s[j][++i[j]]) i[j]=0; // increment the counters
        puts("");
    }
}

```

Basically, *i* are the counters, and *s* the array of strings containing all the chars over which we should iterate, for each counter. The trick is the inner *while* loop: it is used to increment the counters, starting from the rightmost one. If we see that the next character we should display is the ending null char, we restart the counter to zero and the "carry" will be propagated to the next counter.

Thanks Cristoph!

# Answer
> 4 votes
# Befunge, 95 bytes

```
::45*%\45*/:6%\6/:45*%\45*/:6%\6/1g,2g,1g,2g,1g,55+,1+:"}0":**-!#@_
bcdfghjklmnpqrstvwxz
aeiouy

```

Try it online!, although note that the output will be truncated.

This is just a loop over the range 0 to 287999, outputting the index as a mixed based number 20-6-20-6-20, with the "digits" of the number retrieved from the tables on the last two lines.

# Answer
> 4 votes
# Perl 6, 70 bytes

```
$_=<a e i o u y>;my \c=[grep .none,"a".."z"];.say for [X~] c,$_,c,$_,c

```

Explanation of the interesting part:

```
.say for [X~] c, $_, c, $_, c

              c, $_, c, $_, c  # list of five lists
         [X ]                  # lazily generate their Cartesian product
           ~                   # and string-concatenate each result
.say for                       # iterate to print each result

```

The code before that just generates the list of vowels (`$_`) and the list of consonants (`c`), which is regrettably verbose.

# Answer
> 4 votes
# Python 2, ~~120~~ 117 bytes

Thanks to @WheatWizard for the tabs tip.

```
x,y='aeiouy','bcdfghjklmnpqrstvwxz'
for a in x:
 for e in x:
	for b in y:
		for c in y:
			for d in y:print b+a+c+e+d

```

Try it online!

Not sure that this can be golfed much. Try it online truncates at 128KB but shows enough to give an idea. A local run with debug code to count the words gave a total of 288000. Runs in about 45 seconds if anyone wants to test.

```
zyzyv
zyzyw
zyzyx
zyzyz
Total word count: 288000

```

Non-compliant and therefore non-competing version (prints out nested arrays instead of the specified format) for 110 bytes:

```
x,y='aeiouy','bcdfghjklmnpqrstvwxz'
print[[[[c+a+d+b+e for e in y]for d in y]for c in y]for b in x]for a in x]

```

# Answer
> 4 votes
## JavaScript (Firefox 30-57), 82 bytes

```
f=(i=5)=>i?[for(s of f(i-1))for(c of i%2?'bcdfghjklmnpqrstvwxz':'aeiouy')s+c]:['']

```

Returns an array of strings. Very fast version for ~~102~~ 101 (1 byte thanks to @ETHproductions) bytes:

```
_=>[for(i of c='bcdfghjklmnpqrstvwxz')for(j of v='aeiouy')for(k of c)for(l of v)for(m of c)i+j+k+l+m]

```

# Answer
> 4 votes
# Perl 6, 53 Bytes

```
/<-[aeiouy]>**3%<[aeiouy]>/&&.say for [...] <a z>Xx 5

```

Takes a little time to have any output. Very inefficient. Does the job.

# Answer
> 3 votes
# Perl, 71 bytes

```
map{push@{1+/[aeiouy]/},$_}a..z;$"=",";say for glob"{@1}{@2}"x2 ."{@1}"

```

Try it online!

**Explanation**

*I'll add more explanations later.*

`map{push@{1+/[aeiouy]/},$_}a..z;` creates two arrays: `@1` contains the consonants, and `@2` contains the vowels.
`glob` when call with arguments like `{a,b}{c,d}` returns all permutations of the elements in the braces.

# Answer
> 3 votes
# CJam, ~~32~~ ~~31~~ ~~29~~ 28 bytes

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

```
"aeiouy"_'{,97>^\1$1$1$N]:m*

```

Try it online! (Note that the output gets cut off on TIO)

**Explanation**

```
"aeiouy"_ e# Push the six vowels and duplicate
'{,97>    e# Push the whole alphabet
^         e# Symmetric set difference of the alphabet with the vowels, yields the consonants only
\         e# Swap top two elements
1$1$1$    e# Copy the second-from-the-top string to the top three times
          e# This results in the array being consonants-vowels-consonants-vowels-consonants
N         e# Add a newline character to the end of the list
]         e# End an array. Puts everything done so far in an array
          e# since there was no explicit start of the array.
:m*       e# Reduce the array using Cartesian products

```

# Answer
> 3 votes
## Scala, ~~87~~ 86 bytes

```
val a="aeiouy"
val b='a'to'z'diff a
for(c<-b;d<-a;e<-b;f<-a;g<-b)println(""+c+d+e+f+g)

```

# Answer
> 3 votes
# Stacked, noncompeting, 51 bytes

```
(consonants:@c vowels:@v c v c)multicartprod$outmap

```

Pretty simple. Try it here!

# Answer
> 3 votes
# R, ~~111~~ 98 bytes

Added `y` as a vowel, and golfed off 13 bytes, thanks to @Patrick B.

```
l=letters
v=c(1,5,9,15,21,25)
apply(expand.grid(C<-l[-v],V<-l[v],C,V,C)[,5:1],1,cat,fill=T,sep="")

```

We use `expand.grid` to generate all possible combinations of `V` and `C` in a matrix, which we define from the preset variable `letters` (the alphabet). We reverse the combinations (as the default is for the first variable to rotate the fastest) to ensure alphabetical order. Then we iterate through each row of the matrix, printing each letter to stdout. We use the `fill` argument to `cat` to ensure that each word begins on a new line.

# Answer
> 3 votes
# R, ~~143~~ 132 bytes

~~```
q=letters;v=c(1,5,9,15,21,25);x=list(q[-v],q[v],q[-v],q[v],q[-v]);Reduce(paste0,mapply(function(a,b)rep(a,e=b/20),x,cumprod(sapply(x,length))))

```~~
```
q=letters;v=c(1,5,9,15,21,25);x=list(a<-q[-v],b<-q[v],a,b,a);Reduce(paste0,mapply(function(a,b)rep(a,e=b/20),x,cumprod(lengths(x))))

```

This is my first go at code golf so I'd welcome any suggestions to chop it down further. So far it's all pretty standard R; the only possibly tricky thing here is that paste0 recycles its arguments to the length of the longest one.

Edit: used assignment trick from rturnbull, replaced `sapply(x,length)` with `lengths`.

# Answer
> 2 votes
# Perl, ~~63~~ ~~59~~ 54 bytes

~~```
$a="aeiouy";$b="[^$a][$a]"x2;for("a"x5.."z"x5){say if/$b[^$a]/}

```

```
$a="aeiouy";$b="[^$a][$a]"x2;/$b[^$a]/&&say for"a"x5.."z"x5

```~~
```
$a=aeiouy;$b="[^$a][$a]"x2;/$b[^$a]/&&say for a.."z"x5

```

Trying Perl golf for a change.
EDIT: Looks like I've still got much to learn... :)

# Answer
> 2 votes
## C 361 bytes

```
f(){i,j,k,l,m;v[6]={97,101,105,111,117,121};c[25];s=26;for(i=0;i<26;i++)c[i]=97+i;for(i=0;i<26;i++){for(j=0;j<6;j++)if(c[i]==v[j])c[i]+=1;}for(i=0;i<s;i++)for(j=i+1;j<s;){ if(c[i]==c[j]){for(k=j;k<s-1;++k)c[k]=c[k+1];--s;}else ++j;}for(i=0;i<s;i++)for(j=0;j<6;j++)for(k=0;k<s;k++)for(l=0;l<6;l++)for(m=0;m<s;m++)printf("%c%c%c%c%c\n",c[i],v[j],c[k],v[l],c[m]);}

```

Ungolfed version:

```
void f()
{
int i,j, k,l,m;
int s=26;
int v[6]={97,101,105,111,117,121};
int c[s];

for(i=0;i<s;i++)
 c[i]=97+i;
for(i=0;i<s;i++)
{
  for(j=0;j<6;j++)
    if(c[i]==v[j])
      c[i]+=1;
     }
for(i=0;i<s;i++)
 for(j=i+1;j<s;)
 { if(c[i]==c[j])
  {
    for(k=j;k<s-1;++k)
      c[k]=c[k+1];
      --s;
  }else
   ++j;
  }
for(i=0;i<s;i++)
  for(j=0;j<6;j++)
       for(k=0;k<s;k++)
        for(l=0;l<6;l++)
         for(m=0;m<s;m++)
      printf("%c%c%c%c%c\n",c[i],v[j],c[k],v[l],c[m]);
}

```

There must be some way to shorten this definitely.

## Explanation

* Stored the integer values of a,e,i,o,u,y in a numerical array,
* Stored all alphabets in array, if it was a vowel, replaced it with a consonant, so there were duplicate consonant values in the array,
* Removed duplicate consonant values,
* Printed all combinations c-v-c-v-c.

# Answer
> 2 votes
## Clojure, 101 bytes

```
(print(apply str(for[V["aeiouy"]C["bcdfghjklmnpqrstvwxz"]a C b V c C d V e C](str a b c d e "\n")))))

```

Not that exciting...

# Answer
> 2 votes
## Ruby, ~~65~~ 61 bytes

Completely different approach:

```
(b=[*?a..?z]-a="aeiouy".chars).product(a,b,a,b){|x|puts x*""}

```

New things I learned today: the **Array#product** function

# Answer
> 2 votes
# Pyth, ~~25~~ 23 bytes

```
s.n*F[K-GJ"aeiouy"JKJKb

```

In pseudocode:

```
'                       ' G, b = "abcdefghijklmnopqrstuvwxyz", "\n"
'         J"aeiouy"     ' J = "aeiouy"
'      K-GJ             ' K = "bcdfghjklmnpqrstvwxz"
's.n                    ' "".join( flatten(
'   *F                  '   reduce(cartesian_product,
'     [K           JKJKb'     [K,J,K,J,K,b]
'                       ' # b makes it so that every word ends with \n so that
'                       ' # flattening and concatenating automatically deals with
'                       ' # newlines

```

Try it online!

# Answer
> 2 votes
# C#, ~~244~~ ~~242~~ ~~234~~ 219 bytes

```
class P{static void Main(){string v="aeiouy",c="bcdfghjklmnpqrstvwxz";int i=0,j,k,l,m;for(;i<20;i++)for(j=0;j<6;j++)for(k=0;k<20;k++)for(l=0;l<6;l++)for(m=0;m<20;)System.Console.Write("\n"+c[i]+v[j]+c[k]+v[l]+c[m++]);}}

```

Ungolfed:

```
class P
{
    static void Main()
    {
        string v = "aeiouy", c = "bcdfghjklmnpqrstvwxz";
        int i=0, j, k, l, m;
        for (; i < 20; i++)
            for (j=0; j < 6; j++)
                for (k=0; k < 20; k++)
                    for (l=0; l < 6; l++)
                        for (m=0; m < 20; )
                            System.Console.Write("\n"+c[i]+v[j]+c[k]+v[l]+c[m++]);
    }
}

```

I doubt I can trim it any further. Done on C# 5, so no {c\[i\]}

# Answer
> 2 votes
## Batch, 185 bytes

```
@set c=b c d f g h j k l m n p q r s t v w x z
@for %%i in (%c%)do @for %%j in (a e i o u y)do @for %%k in (%c%)do @for %%l in (a e i o u y)do @for %%m in (%c%)do @echo %%i%%j%%k%%l%%m

```

Batch is so verbose that it costs 4 bytes to put the vowels into a variable.

# Answer
> 2 votes
## T-SQL, 276

This answer assumes a query's result set is valid output.

```
WITH c AS(SELECT*FROM(VALUES('b'),('c'),('d'),('f'),('g'),('h'),('j'),('k'),('l'),('m'),('n'),('p'),('q'),('r'),('s'),('t'),('v'),('w'),('x'),('z'))c(_)),v AS(SELECT*FROM(VALUES('a'),('e'),('i'),('o'),('u'),('y'))v(_))SELECT c._+v._+b._+a._+d._ FROM c,v,c b,v a,c d ORDER BY 1

```

It works in SQL Server 2008 R2. I'm not sure currently where you'd be able to run it online given the number of rows returned, though.

One CTE definition holds the consonants from a derived table. The other holds the vowels from another derived table. Take the Cartesian product of three consonant CTEs and two vowel CTEs, and you can get an alphabetized list of the appropriately concatenated values.

# Answer
> 2 votes
# Jelly, 10 bytes

```
ØỴ,Øỵṁ5ŒpY

```

Try it online!

# Answer
> 1 votes
# Haskell, 93 bytes

```
c="bcdfghjklmnpqrstvwxz"
t=[[a,b]|a<-"aeiuoy",b<-c]
main=putStr$unlines[b:y++z|b<-c,y<-t,z<-t]

```

I have tried to slim the hardcoded lists of consonants and vowels down, but haven't been able to find something that saves bytes. This will output all possible five letter words in the order as stated in the post to stdout, being generated via list comprehensions.

# Answer
> 1 votes
# Java, 347 bytes -.-

```
public class N{public static void main(String[]a){String c="bcdfghjklmnpqrstvwxz";String v="aeiouy";int[]i=new int[5],e=new int[5];e[0]=e[2]=e[4]=20;e[1]=e[3]=6;m:while(true){System.out.println(c.charAt(i[0])+v.charAt(i[1])+c.charAt(i[2])+v.charAt(i[3])+c.charAt(i[4]));int p=4;while(true){++i[p];if(i[p]<e[p])break;i[p]=0;if(p==0)break m;--p;}}}}

```

# Answer
> 1 votes
# Informix-SQL, 254 bytes

an SQL version (IBM Informix dialect)

```
select x from table(list{'a','e','i','o','u','y'})(x)
into temp v;
select x from table(list{'b','c','d','f','g','h','j','k',
'l','m','n','p','q','r','s','t','v','w','x','z'})(x)
into temp c;
select k.x||j.x||i.x||v.x||c.x
from c,v,c i,v j,c k
order by 1

```

# Answer
> 1 votes
# , <sup>~~52~~</sup> <sup>~~37~~</sup> <sup>~~34~~</sup> 33 bytes

```
echo>,{5$'aeiouy'(-.~;[)u:97+i.26

```

Try it online!

*-1 thanks to Adam's suggestion of `u:97+i.26` to replace `26{.97|.a.`*

* `u:97+i.26` extract letters a..z from ascii alphabet `a.`
* `'aeiouy'(-.~;[)` subtract the vowels from a..z, and link `;` that (the consonants) to the vowels, creating a boxed list `consonants ; vowels`.
* `5$` extent that boxed list cyclically to 5 elements, yielding `consonants ; vowels ; consonants ; vowels ; consonants`.
* `{` create the cross product
* `,` flatten
* `>` open the boxes to create regular strings
* `echo` print the results

# Answer
> 1 votes
# Brachylog v2, 11 bytes

```
Ḍ;Ẉj,Ḍ∋ᵐcẉ⊥

```

Try it online!

Pretty much the same as Fatalize's Brachylog v1 answer.

# Answer
> 1 votes
# Shell, ~~72~~ 64

Try it online! (Thanks @Grimy)

`echo {g..z}{a..f}{g..z}{a..f}{g..z}|tr b-z eiouybcdfghj-np-tvwxz`

---

If it must be delimited by newlines (beware of the spaces) 69 bytes Try it online!:

`echo {g..z}{a..f}{g..z}{a..f}{g..z}|tr \ b-z \\neiouybcdfghj-np-tvwxz`

---

Original shell, 72 bytes (bash, ksh, zsh, a simple sh may not expand `{..}`) Try it online!

`echo {a..t}{1..6}{a..t}{1..6}{a..t}|tr a-t1-6 bcdfghjklmnpqrstvwxzaeiouy`

Less than half a second. Considering that a C equivalent runs in 0.228sec and a perl equivalent takes 2.1 seconds, this is **Not** slow (times reported as TiO measured them).

# Answer
> 1 votes
# Zsh, 58 bytes

```
v=(a e i o u y)
c=(${${:-{b..z}}:|v})
echo $^c$^v$^c$^v$^c

```

Try it online!

`${ :|foo}` is set difference, and `${^foo}` enables brace expansion over the contents of the array `foo`.

---

If newline-delimited is required, **64 bytes**:

```
v=(a e i o u y)
c=(${${:-{b..z}}:|v})
<<<${(F):-$^c$^v$^c$^v$^c}

```

Try it online!

# Answer
> 1 votes
# Vyxal, 8 bytes

```
k¹k∪"5ẎΠ

```

Try it Online!

```
    "    # Pair
k¹       # Consonants
  k∪     # and vowels
     5Ẏ  # Extend to length 5
       Π # Take the cartesian product

```

# Answer
> 1 votes
# K (ngn/k), <sup>40</sup> 35 bytes

```
+x@'!#'x:1_5^[`c$97+!26;]\"aeiouy"

```

Try it online!

-5 : clever shuffling from @ngn. Constant alphabet, alternating set differences.

# Answer
> 1 votes
# Zsh `-P`, 54 bytes

```
v=(a e i o u y)
c=({a..z})
c=(${c:|v})
echo $c$v$c$v$c

```

Attempt This Online!

# Answer
> 1 votes
# Perl 5, 40 bytes

```
y/aeiouy/1/r=~/\D1\D1\D/&&say for a..1x5

```

Try it online!

# Answer
> 0 votes
# C (gcc), ~~123~~ ~~120~~ 117 bytes

-6 bytes thanks to ceilingcat

```
char w[6];f(n,m,c,p){for(n=457653;c=p=n<1<<24;p&&puts(w))for(m=n++;m;m/=26)p*=!index("aeiouy",w[5-c]=m%26+97)^++c%2;}

```

Try it online!

# Answer
> 0 votes
# MathGolf, ~~25~~ 16 bytes

```
╩æ╩¼`┼]m▒ε*mÅ─yn

```

Try it online!

~~Definitely not optimal, but this challenge got me to actually implement some features of MathGolf that have been in TODO since forever, mainly string subtraction and vowels/consonants. Once it's up on TIO I'll update this answer.~~ MathGolf has been updated, and I'll add this as a disclaimer that some features used in this answer are newer than the challenge itself.

To fetch consonants and vowels from the dictionary, I filtered out words in the dictionary files which were duplicates, and found that I had 3 duplicates within the top 256 words of the dictionary. I decided that that 2 of these slots should be replaced by the string of consonants and the string of vowels. I was unsure of where "y" should be placed, but decided to place it among the vowels.

The one thing that is not in place is cartesian product for strings. Since I have not defined the output format yet, this feature did not make it into the latest version of MathGolf.

## Explanation

```
╩æ                 fetch dictionary word 145 ("bcdfghjklmnpqrstvwxz")
  ╩¼               fetch dictionary word 172 ("aeiouy")
    `              duplicate the top two items
     ┼             duplicate second item from top and push to top
      ]            end array / wrap stack in array
                   stack is now ["<cons>", "<vow>", "<cons>", "<vow>", "<cons>"]
       m▒          map each element to a list of chars
         ε*        reduce list by multiplication (cartesian product)
           mÅ      explicit map using next 2 operators
             ─     flatten array
              y    join array without separator to string or number
               n   join array with newlines to a string

```

# Answer
> 0 votes
# ink, 224 bytes

```
LIST V=(a),e,i,o,u,y
LIST C=(b),c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,z
~temp D=C
~temp E=V
~temp F=C
~temp G=V
~temp H=C
-(L){D}{E}{F}{G}{H}
~H++
{H:->L}
~H=C
~G++
{G:->L}
~G=V
~F++
{F:->L}
~F=C
~E++
{E:->L}
~E=V
~D++
{D:->L}

```

Try it online!

# Answer
> 0 votes
# Curry (PAKCS), 57 bytes

```
v=anyOf"aeiouy"
c=anyOf"bcdfghjklmnpqrstvwxz"
[c,v,c,v,c]

```

Attempt This Online!

# Answer
> 0 votes
# JavaScript (Node.js), 80 bytes

```
f=(i=5,s)=>i?[...i%2?'bcdfghjklmnpqrstvwxz':'aeiouy'].flatMap(e=>f(i-1,[s]+e)):s

```

Try it online!

# JavaScript (Node.js), 99 bytes

```
f=(i=5,s='',j=35,c=j.toString(36))=>+c?'':i?f(i,s,j-1)+(i%2^/[aeiouy]/.test(c)?f(i-1,s+c):''):s+' '

```

Try it online!

# Answer
> 0 votes
# Regenerate `-a`, 82 bytes

```
[bcdfghjklmnpqrstvwxz][aeiouy][bcdfghjklmnpqrstvwxz][aeiouy][bcdfghjklmnpqrstvwxz]

```

Attempt This Online!

Unfortunately, there's no clever way to do this in Regenerate--just gotta list all the options.

---
Tags: code-golf, string, kolmogorov-complexity, combinatorics
---


title: Print out all IPv6 addresses

text:
# Question
Title: Print out all IPv6 addresses
> This reminds me when a few years ago someone uploaded a torrent "Hacker tool: complete list of all IP addresses". This was, of course, just a generated list of the ~4 billion IPv4 addresses, but thousands of "h4xx0rz" downloaded it. Look mum, imahacker!

This was then, but nowadays everybody has switched to IPv6. (Right?)

Your task is to write a program that **prints out all IPv6 addresses**.

You should write a full program that takes no input and prints IPv6 addresses, one per line, and no other output. Your program must print all 2128 possible addresses, including invalid ones. Each address must be printed exactly once. You may print the addresses in any order.

Each address may be printed in full, with 8 groups of 4 hexadecimal digits separated by colons, e.g.

```
2001:0db8:85a3:0000:0000:8a2e:0370:7334

```

You may, at your discretion, use any of the standard abbreviations from RFC 5952:

* Leading zeros in a group may be omitted, except that `0` cannot be abbreviated further.
* `::` may be used at most once per address to abbreviate a sequence of one or more all-zero groups.
* The hexadecimal digits may use lowercase or uppercase.

If you achieve the representation recommendation from RFC 5952 (lowercase letters only, shortest possible representation, with `::` used as early as possible if there are multiple places where it can be used), you get a **-20% bonus**.

Due to the size of the output, your program is not expected to finish while we're sitting there. Your program may be interrupted by external means at some point (`Ctrl`+`C`, pulling out the power, …). Your program must produce output as a stream, so that after a “reasonable” wait, it will have produced some lines. Basically, building a giant string in memory only to print it at the end is not allowed. Any program that would run out of memory on a “standard” PC is disqualified. (Nonetheless, if your program was left to run for sufficiently long, it must print all IPv6 addresses and then exit.)

(If this condition is a problem for web interpreters that run the program until completion and then let you see the output, and you don't have a hosted interpreter, test your program on a smaller version of the problem, and then carefully adjust it to the full 2128.)

Your score is your program's length in bytes, multiplied by 0.8 if you get the bonus. It's code golf, so the lowest score wins.

# Answer
# Pyth, 21 bytes

```
KJ^8CdWJj\:ct.H+K=tJ4

```

Uses a while loop with `J` as the iterator variable. Initializes the maximum using `8^chr(' ')`. Pads by adding that initial value, converting to hex, then removing the first character.
> 6 votes

# Answer
# Python 3, 65 bytes · 0.8 = 52.0

```
from ipaddress import*
n=4**64
while n:n-=1;print(IPv6Address(n))

```
> 53 votes

# Answer
# Pyth, ~~27~~ ~~25~~ 24 bytes

*Note: the code had a bug previously, fixing it saved 1 byte*

```
J^4 64WJj\:c%"%032x"=tJ4

```

Prints the addresses like

```
ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff
ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe
ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffd
ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffc
...
0000:0000:0000:0000:0000:0000:0000:0003
0000:0000:0000:0000:0000:0000:0000:0002
0000:0000:0000:0000:0000:0000:0000:0001
0000:0000:0000:0000:0000:0000:0000:0000

```

Previous (more complicated) version using the pad operator (also 24 bytes):

```
J^4 64WJj\:c.[\032.H=tJ4

```

### Explanation

```
J^4 64                  set J to 2^128
WJ                     while J is not 0:
            =tJ               decrement J
    %"%032x"                 format to length-32 hex string
   c           4            split every 4 chars
j\:                        join by : and print

```

## Pyth, 21 bytes (invalid)

```
jmj\:c.[\032.Hd4^4 64

```

This can't be run since 1) it would consume at least 2132 bytes (252 yobibytes) of memory and 2) the interpreter doesn't like it (2128 doesn't fit in `ssize_t`, so no `list`s of that size). It would print the addresses in lexicographical order. You can try out the algorithm by changing the number(s) in the end to something usable.
> 14 votes

# Answer
# C (with GCC extensions), 76 bytes * 0.8 = 60.8

```
__uint128_t i;main(){char s[50];for(;inet_ntop(10,&i,s,49),puts(s),++i>0;);}

```

This uses the 128-bit integers GCC extension to simply count up from `::` to `ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff`. `inet_ntop()` correctly formats each address so the -20% bonus can be claimed.

### Output

Using `sed` to output every millionth line up to 10 million:

```
$ ./ipv6all | sed -n '1~1000000p;10000000q'
::
4042:f00::
8084:1e00::
c0c6:2d00::
9:3d00::
404b:4c00::
808d:5b00::
c0cf:6a00::
12:7a00::
4054:8900::
$

```

Note I am using a little-endian x86\_64 machine, and that network addresses are typically always in network-order (big-endian), so the endianness is effectively swapped by using `inet_ntop()`. This does not matter - all addresses will still (eventually) be displayed.
> 12 votes

# Answer
# CJam, ~~36~~ 27 bytes

```
G32#{(_"%032x"e%4/':*oNo}h;

```

-9 bytes thanks to @Dennis (I forgot that CJam has string formatting). Prints the addresses lowercase and descending.

For obvious reasons, use the Java interpreter, not the online one. You can replace `G32#` with something smaller for testing online though, e.g. here's the last 100.

### Explanation

```
G32#             16^32 = 2^128. Call this n
{ ... }h;        While loop. The final ; is to pop n at the end
 (               Decrement n
 _               Copy n
 "%032x"e%       String format to hex, padded to 32 digits
 4/              Split into groups of 4
 ':*             Join with colons
 oNo             Output with newline

```
> 11 votes

# Answer
# Python 2.7, 67 bytes

```
n=4**64
while n:n-=1;s='%032x'%n;exec"s=s[4:]+':'+s[:4];"*7;print s

```

As a side effect of the method used to insert the colons, the addresses are printed with the rightmost column appearing at the left:

```
ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff
fffe:ffff:ffff:ffff:ffff:ffff:ffff:ffff
fffc:ffff:ffff:ffff:ffff:ffff:ffff:ffff
...
0003:0000:0000:0000:0000:0000:0000:0000
0002:0000:0000:0000:0000:0000:0000:0000
0001:0000:0000:0000:0000:0000:0000:0000

```
> 8 votes

# Answer
# Cinnamon Gum, 16 bytes

```
0000000: 678b 36d0 b54c d44d 8bc5 455b 8d0c 0500  g.6..L.M..E[....                               .

```

Try it online. (TIO limits output)

## Explanation

The `g` mode puts Cinnamon Gum in *generate mode*. The rest of the string decompresses to this regex:

```
[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]

```

It then creates a generator of all possible strings that match the regex and iterates through it, printing out each one.

Somewhat amusingly, the golfier regex `([0-9a-f]{4,4}:){7,7}[0-9a-f]{4,4}` actually compresses to a longer string than the regex above.
> 8 votes

# Answer
# Verilog, 335

My first Verilog submission, probably could use more golfing but I don't have the energy to do so right now. `c` is clock, `o` is ASCII output. Does not qualify for formatting bonus due to zero-padding instead of abbreviating.

```
module b(output[0:38]o,input c);reg[127:0]a;wire[0:39]d;assign o=d[0:38];always @(posedge c) a<=a+(~(&a));genvar i,j;generate for(i=0;i<8;i=i+1) begin:q for(j=0;j<4;j=j+1) begin:r assign d[5*i+j]=a[16*i+4*j:16*i+4*j+7]>9?{4'h6,a[16*i+4*j:16*i+4*j+7]-9}:{4'h3,a[16*i+4*j:16*i+4*j+7]};end assign d[5*i+4]=8'h3A; end endgenerate endmodule

```

This is a simple iteration followed by some bit-twiddling to make the output ASCII. I chop the colon after the last group with a small hack. Synthesizes and appears to work for xc3s500e-4ft256-4 on ISE 13.7 lin64.
> 7 votes

# Answer
# C, 91-126 bytes

My original version, 119 bytes.

```
long a[9],i;
f(long*x){if(65536&++*x)*x=0,f(x+1);}
main(){for(;!a[8];f(a))for(i=7;i+1;i--)printf(i?"%lx:":"%lx\n",a[i]);}

```

Best golfed portable-ish version, 103 bytes (thanks @Dennis for some of these concepts)

```
long*p,a[9];
main(i){while(!a[8]){
for(i=8;i--;printf(i?"%lx:":"%lx\n",a[i]));
for(p=a;++*p>>16;*p++=0);}}

```

Explanation: The algorithm itself is reasonably straightforward. I used long rather than unsigned int because it's shorter. Declaring them at the file level means everything's preinitialized with zeros. The `f` function is a simple increment with carry that operates on the low 16 bits of each word. The loop ends when it carries into the 129th bit.

Iterating backwards for the printf means that we print the addresses in the "proper" order and also the check for printing a newline is a few characters shorter.

This does use some non-portable constructs. It's best regarded as a K&R dialect of C, since it uses implicit int return types and does not include stdio.h. And my use of long was informed by this - on most modern systems int is sufficient because it's 32 bits. This could probably run unmodified on PDP-11 Unix.

However, it can be shorter. If we assume that we can use int (either as a type wider than 16 bits, or a type of exactly 16 bits with various properties that happen to be true on many systems such as twos complement and arithmetic rollover), we can get rid of the stuff related to using long.

Version for int wider than 16 bits, 97 bytes.

```
a[9],*p;main(i){while(!a[8]){
for(i=8;i--;printf(i?"%x:":"%x\n",a[i]));
for(p=a;++*p>>16;*p++=0);}}

```

Version for 16-bit systems, 91 bytes.

```
a[9],*p;main(i){while(!a[8]){
for(i=8;i--;printf(i?"%x:":"%x\n",a[i]));
for(p=a;!++*p;p++);}}

```

Oddly enough, though, the original K&R compiler didn't actually support the declaration without int (it compiles fine, but treats the variables as external and therefore undefined at link time), so an additional three bytes are needed to change the declaration to `int*p,a[9];` for a total of 94.

Also, if the assumption that it is interrupted before completing output were a hard constraint, we could remove the end check, saving five bytes.

Bonus: fully ANSI portable version, 126 bytes:

```
#include<stdio.h>
long*p,i,a[9];
int main(){while(!a[8]){
for(i=8;i--;printf(i?"%lx:":"%lx\n",a[i]));
for(p=a;++*p>>16;*p++=0);}}

```

Newlines in all versions are inserted for readability and in locations where whitespace is not required, and are excluded from the byte count, except for the newline after the `#include` line in the ANSI version.

All versions except the ANSI version fall through at the end of main and therefore may return a spurious exit code to the operating system.
> 6 votes

# Answer
# AutoIt3, ~~142~~ 231 Bytes

```
For $a=0 To 2^32-1
For $b=0 To 2^32-1
For $c=0 To 2^32-1
For $d=0 To 2^32-1
$s=StringFormat("%08x%08x%08x%08x",$a,$b,$c,$d)
For $j=0 To 8
ConsoleWrite(StringMid($s,$j*4+1,4)&($j<7?":":""))
Next
ConsoleWrite(@LF)
Next
Next
Next
Next

```

## Explanation

* `For $a=0 To 2^32-1`: Iterate 4 times over 0-2^32 ((2^32)^4=2^128) possible combinations.
* `$s=StringFormat("%08x%08x%08x%08x",$a,$b,$c,$d)`: Convert the numbers to a hexadecimal string with a length of 32 (4\*32).
* `For $j=0 To 8`: Iterate over all 8 sections of the string.
* `ConsoleWrite(StringMid($s,$j*4+1,4)&($j<7?":":""))`: Extract the next 4 characters from the string and add a colon (`:`) at the end, if we haven't reached the last section, then output everything to the console
* `Next`: End the inner for-loop
* `ConsoleWrite(@LF)`: Add a line-feed at the end of the line
* `Next`: End the outer for-loops

Expected output size: (One line (39 bytes) + line-feed) (=40 bytes) * 2^128 = 1.361\* 10^16 YB (yottabytes)
> 5 votes

# Answer
# Commodore BASIC 2.0, 339 bytes

In order to get lower-case hex digits, this program is written in "shifted mode" (press `<SHIFT>+<C=>`)

```
1k=65535:a=0
2fOb=0tok:fOc=0tok:fOd=0tok:fOe=0tok:fOf=0tok:fOg=0tok:fOh=0tok
3x=a:goS6:?":";:x=b:goS6:?":";:x=c:goS6:?":";:x=d:goS6:?":";:x=e:goS6:?":";:x=f
4goS6:?":";:x=g:goS6:?":";:x=h:goS6:?
5nE:nE:nE:nE:nE:nE:nE:nE:a=a+1:ifa<65536tH2
6y=x/4096:goS7:y=x/256aN15:goS7:y=x/16aN15:goS7:y=xaN15:goS7:reT
7?mI("0123456789abcdef",y+1,1);:reT

```

Simply making this *work* on the Commodore 64 was a challenge, because of memory, screen size, data size, and other limitations. I considered implementing the abbreviated representation, but other limitations (such as the undocumented inability to use array elements as loop indices) meant it would increase the length of the program by an estimated 1000 bytes.

Line 7 is an implementation of `HEX$()`, which Commodore BASIC 2.0 is lacking. I can't use a `DEF FN` for this because those can only return numbers, not strings. Line 6 is a subroutine that applies it to a group of four digits, which would have been considerably shorter if functions could return strings.

Lines 2 and 5 are eight nested loops, implemented as seven "for" loops and a conditional goto because eight "for" loops, when combined with the two "gosubs" for printing out the address, will overflow the C64's tiny stack.

A C64 can print out about 1.2 addresses per second, for an estimated runtime of 1.3\*10^31 years.
> 5 votes

# Answer
### PowerShell (v4), 193 166 162 145 103 bytes

TimmyD's no-bonus version at 103 bytes:

```
$i=[bigint]::Pow(4,64);while($i-gt0){('{0:X32}'-f($i-=1)-replace'0(?=.{32})'-replace'.{4}(?!$)','$0:')}

```

---

Previous with-bonus version at 145 * 0.8 = 116 bytes

With help from TimmyD and tomkandy, who points out that `0 -eq $false` but `([bigint]0) -eq $true`. So all my previous versions won't terminate.

```
$i=[bigint]::Pow(4,64);while($i-gt0){$i-=1;[IPAddress]::Parse((('{0:X32}'-f$i
)-replace'0(?=.{32})'-replace'.{4}(?!$)','$0:')).IPAddressToString}

```

---

Previously at 162, before some regex changes:

```
$i=[bigint]::Pow(4,64)
while($i){$i-=1;if(($x='{0:X32}'-f$i).Length-eq33){$x=$x.Substring(1)}
[IPAddress]::Parse(($x-replace'.{4}(?!$)','$0:')).IPAddressToString}

```

*"A challenge where PowerShell ought to be reasonably competetive!"* \- me, before I tried it.

**Explanation**

```
# PowerShell (PS) has no IP address arithmetic, e.g. IP + 1
#- PS has no 128 bit integers
#- PS has no automatic bignums

# Start from the top, with the BigInteger specialised Power()
$i = [BigInt]::pow(4,64)

# Loop 4**64 through 1, work with $i-1 for ff... -> ::0
while ($i) {
    # PS has no decrement operator for bignums
    # (no using $i-- in the while loop test)
    $i-=1

    # The Net.IPAddress class can't turn a BigInteger
    # into an IPv6 address directly. And because it mashes
    # IPv4 and IPv6 into one class, there's no obvious way
    # to make a small number always cast to an IPv6 address.
    # Format the bignum as a string of 32 hex digits.
    $x = '{0:X32}' -f $i

    # The BigInteger often formats as /33/ hex digits,
    # with a leading zero (to avoid unintentional +/- sign bits)
    # ( https://msdn.microsoft.com/library/dd268287 )
    # So remove the leading 0, if there is one
    if (($x).Length-eq33){$x=$x.Substring(1)}

    # I can't always remove the leading zero, because it
    # can't parse FFFFF... into an address without colons
    # and this regex replace into groups of 4 with colons
    # would go wrong at length 31. No : after the last group
    # This is still better than split/join ... because there
    # isn't a split-into-groups-of-N that I know of.
    $x = ($x -replace '.{4}(?!$)', '$1:'

    # Woo! * 0.8 bonus! 45 characters to save 38! :D
    [IPAddress]::Parse($x).IPAddressToString

}

```
> 4 votes

# Answer
# AutoIt3, 137 Bytes

```
For $i=0 To 4^64
$s=StringFormat("%032x",$i)
For $j=0 To 7
ConsoleWrite(StringMid($s,$j*4+1,4)&($j<7?':':''))
Next
ConsoleWrite(@LF)
Next

```
> 3 votes

# Answer
# Regenerate `-a`, 24 bytes

```
(($3:!)[0-9a-f]{4}()){8}

```

Attempt This Online!

```
(
    # Match ":" iff we're not on the first iteration
    (
        $3        # Match iff we're not on the first iteration
        :         # Match ":"
    !             # Short-circuiting alternation - only try matching the below
                  # if it was impossible for the above to match.
                  # Do nothing
    )
    [0-9a-f]{4}   # Match 4 hexadecimal digits
    ()            # $3 = signal that we're not on the first iteration anymore
)
{8}               # Repeat the above 8 times

```

Alternative 24 bytes:

```
(({#1}:!)[0-9a-f]{4}){8}

```

Attempt This Online!

It might not be intended that this is possible, but Regenerate allows a quantifier to be preceded by nothing. This is what's happening with `{#1}` \- it's impossible for it to match on the first iteration because `$1` hasn't been captured yet and doesn't have a length. On subsequent iterations, a match of nothing gets repeated 4 times (the length of `$1`).
> 3 votes

# Answer
# Ruby 75

```
x=->s,n{n>0?65536.times{|m|x.(s+?:*(8<=>n)+m.to_s(16),n-1)}: p(s)};x.('',8)

```

This is a recursive solution that takes a each prefix and finds every possible suffix. Recursively.
> 2 votes

# Answer
# Python 2, 95 bytes

```
def i(p=0):
 while p<4**64:print':'.join(hex(p)[2:].zfill(32)[4*s:4*s+4]for s in range(8));p+=1

```

Simply goes through every number from 0 to 2^128. First it converts the current number to hexadecimal string, then strips off the `'0x'` that that function gives. Next it adjusts the string to have 32 zeros in the front and then breaks it up into groups of four. Finally it joins the groups of four with colons, prints that out and adds 1 to the current number. Has the added bonus that you can start it at any value if you give it one, but no input is needed.
> 2 votes

# Answer
# Haskell 111

```
s[]=[[]]
s(a:b)=[y:z|z<-s b,y<-a]
r=replicate
main=mapM putStrLn$s$tail$concat$r 8$":":r 4"0123456789abcdef"

```

With my own sequence function `s` it no longer leaks memory, but does not feel golfed any more.
> 2 votes

# Answer
# CBM BASIC v7.0 (166 characters)

```
a=65535
fOi=0toa:fOj=0toa:fOk=0toa:fOl=0toa:fOm=0toa:fOn=0toa:fOo=0toa:fOp=0toa:?hE(i)":"hE(j)":"hE(k)":"hE(l)":"hE(m)":"hE(n)":"hE(o)":"hE(p):nE:nE:nE:nE:nE:nE:nE:nE

```

Mark's answer is for the Commodore 64's BASIC 2.0, which lacks a built-in command for printing numbers in hexadecimal. However, thanks to the `HEX$()` function in BASIC 7.0, the Commodore 128 version is much shorter. It doesn't fit on a single logical line (which on the C128 is limited to 160 characters) but can still be entered as two separate lines in direct mode.
> 2 votes

# Answer
# Zsh `-P`, 60 bytes

```
x=({0..9} {a..f})
eval for\ {1..8}' ($x$x$x$x)<<<${(j/:/)@}'

```

Attempt This Online! (Warning: if you don't click the kill button fairly quickly, your browser will run out of memory and crash)

`eval for\ {1..8}` creates 8 nested loops using the loop variables `$1`, `$2`, ..., `$8`. These numbered variables can then be referred to implicitly using `$@` (here, they're joined with colons using `${(j/:/)}`).

The `<<<${...}` section is actually repeated for each level of nested loop as well, but (apart from the last one) they all do nothing, because they feed into the next loop, which ignores its input.

The `-P` option enables an implicit cartesian product on the adjacent expansions `$x$x$x$x`. This is the shortest way I could find to count up to `0xffff` *in hex* without needing to convert each loop variable to hex individually.
> 2 votes

# Answer
# Vyxal, 21 bytes

```
₇E(nk6τ₅32ε\0*p4ẇ\:j,

```

Try it Online!

Ugh, we really need a zfill builtin.
> 1 votes

# Answer
# Go, \\$243 \times 0.8 = \\$ 194.4 bytes

```
import(."fmt";."net/netip")
func F(){for a,M:=0,1<<32-1;a<M;a++{for b:=0;b<M;b++{for c:=0;c<M;c++{for d:=0;d<M;d++{s:=""
for n,k:=0,Sprintf("%08x%08x%08x%08x",a,b,c,d);n<8;n++{s+=k[4*n:4*(n+1)]+":"}
A,_:=ParseAddr(s[:len(s)-1])
Println(A)}}}}}

```

Attempt This Online!

Prints to STDOUT. Uses the `netip.Addr` type from the Golang standard library to do the formatting for me.

### Explanation

```
import(."fmt";."net/netip")
func F(){
for a,M:=0,1<<32-1;a<M;a++{ // first 8 digits
for b:=0;b<M;b++{           // next  8 digits
for c:=0;c<M;c++{           // next  8 digits
for d:=0;d<M;d++{           // final 8 digits
k:=Sprintf("%08x%08x%08x%08x",a,b,c,d)  // join the numbers into a single string
s:=""
for n:=0;n<8;n++{s+=k[4*n:4*(n+1)]+":"} // split into 8 groups of 4, split by colons
A,_:=ParseAddr(s[:len(s)-1])            // parse the address
Println(A)}}}}}                         // print using the default String() method, which formats the address

```
> 1 votes

# Answer
## Tcl ~~341~~ ~~318~~ 301

```
proc ip6 {p c} {
    set s %x:%x:%x:%x:%x:%x:%x:%x
    set p [scan $p $s]
    while {[set d 7]} {
        $c [format [string map {x 04x} $s] {*}$p]
        while {[set i [lindex $p $d]]==0xFFFF} {
            lset p $d 0
            if {!$d} return
            incr d -1
        }
        lset p $d [incr i]
    }
}
ip6 fFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:0000 puts

```
> 0 votes

---
Tags: code-golf, kolmogorov-complexity
---


title: Was it a King or a Queen or neither?

text:
# Question
Title: Was it a King or a Queen or neither?
# Input

A calendar year from 927 to 2022.

# Output

You can use any three distinguishable outputs. As an example,

“K” (short for King)

or

“Q” (short for Queen)

depending on which of the two England had in that year. If there was both a King and Queen in that year you can output either.

If there was no King or Queen for the whole of that year, your code must output something that is not one of those two messages.

# Dates

Kings: 927-1553, 1603-1649, 1660-1702, 1714-1837, 1901-1952, 2022

Queens: 1553-1603, 1689-1694, 1702-1714, 1837-1901, 1952-2022

Neither: 1650-1659

# Answer
> 42 votes
# Squire, 194 characters

```
d=tally(inquire())i=\(d,s,e)=>s<=d&&d<=e;o=;if i(d,MDCL,MDCLIX){o= }alas if i(d,MCMLII,MMXXII)||i(d,MDCCCXXXVII,MCMI)||i(d,MDCCII,MDCCXIV)||i(d,MDLIII,MDCIII){o=}proclaim(o)

```

This contest doth be marvelously suited for ye medieval-inspired parlance, Squire. Whilst Squire doth hath a veritable cornucopia of features, lamentably suitability for golfing doth be nary amongst them.

Squire only has roman numeral literals, as well as some fairly length constructs (e.g. `inquire`, `tally`, `proclaim`), so it's not as short as other languages. On the plus side, squire has bare words—however only when the strings are comprised entirely exclusively of the unicode fraktur characters or whitespace.

Unfortunately, the interpreter is not able to fit onto TIO or anything else, so if you want to test it you'll need to build locally...

Ungolfed, the program is:

```
N.B. Journeys are functions, and you get a reward for returning from them.
journey in(date, start, end) {
    reward start <= date && date <= end
}

N.B. `tally` converts to a number, `inquire` reads from stdin.
N.B. In addition to roman numerals, `tally` also reads arabic ones too.
date = tally(inquire())

N.B. Using the fraktur literals, set the default value for `whom`.
N.B. This is sugar for "King".
whom = ; N.B. The `;` is needed here because the parser is bad lol

N.B. Check to see if the date is within Cromwell's time.
if in(date, MDCL, MDCLIX) {
    whom =
} alas if
    in(date, MCMLII, MMXXII)
    || in(date, MDCCCXXXVII, MCMI)
    || in(date, MDCCII, MDCCXIV)
    || in(date, MDLIII, MDCIII)
{
    whom =
}

N.B. The printing press wasn't around way back when. So instead we have
N.B. the town crier proclaim our outputs.
proclaim("The {whom} reigned during the year {date}")

```

# Answer
> 21 votes
# JavaScript (Node.js), 50 bytes

Returns \\$0\\$ for Queen, \\$1\\$ for King, or \\$2\\$ for neither.

This code includes some unprintable characters.

```
y=>2132%Buffer(`2/
+{@3`).find(c=>(y-=c)<1542)&3

```

Try it online!

### How?

The ASCII codes of the data string are:

```
[ 11, 50, 47, 10, 43, 12, 123, 64, 51 ]

```

They represent the number of years to be added to get the exclusive upper bound of the next interval, starting at \\$1542\\$.

Once the correct interval has been identified, we apply the following formula to its encoding number \\$N\\$ to figure out whether it was a King, a Queen or neither:

$$(2132 \bmod N)\bmod 4$$

The last interval is not explicitly encoded. For any input greater than \\$1952\\$, `find()` returns `undefined` which is turned into `NaN`. But because we use a bitwise AND with \\$3\\$ rather than an actual modulo \\$4\\$, it is eventually coerced to \\$0\\$ -- the expected result for Queen Elizabeth II.

| N | Exclusive upper bound | Interval | 2132 mod N | and 3 | Result |
| --- | --- | --- | --- | --- | --- |
| 11 | 1553 | 927 - 1552 | 9 | 1 | King |
| 50 | 1603 | 1553 - 1602 | 32 | 0 | Queen |
| 47 | 1650 | 1603 - 1649 | 17 | 1 | King |
| 10 | 1660 | 1650 - 1659 | 2 | 2 | Neither |
| 43 | 1703 | 1660 - 1702 | 25 | 1 | King |
| 12 | 1715 | 1703 - 1714 | 8 | 0 | Queen |
| 123 | 1838 | 1715 - 1837 | 41 | 1 | King |
| 64 | 1902 | 1838 - 1901 | 20 | 0 | Queen |
| 51 | 1953 | 1902 - 1952 | 41 | 1 | King |
| undefined | n/a | 1953 - ... | NaN | 0 | Queen |

# Answer
> 11 votes
# Python 3, 60 bytes

A function that returns `0` for **King**, `1` for **Queen**, and `2` for **Neither**.

```
lambda n:sum(c>n-ord('ؑٱڦޟܭ'[c%5])>0for c in b'2@I')

```

Try it online!

# Answer
> 8 votes
# Knight (v2.0-alpha), 78 bytes

```
O I|>927=xP?GxF3'165'0I|&<1553x<1603x|&<1702x<1714x|&<1837x<1901x&<1952x<2022x

```

Try it online!

Nothing special, just check for ranges with `<` and `>`. Since we have to output just three distinct things, `0` is for when it's neither, `true` for a queen and `false` for a king. Slightly unminified:

```
O I|>927=xP?GxF3'165'0
  I|&<1553x<1603x
   |&<1702x<1714x
   |&<1837x<1901x
    &<1952x<2022x

```

# Answer
> 6 votes
# Python 3.8,  ~~58~~  57 bytes

```
lambda y:9%(6-sum((y:=y-v)<1500for v in b'61/\n+|?4'))%2

```

(Contains an unprintable byte between `+` and `|`.)

An unnamed function that accepts an integer from \\$\[927,2022\]\\$ and:

* produces a `ZeroDivisionError` for years when neither a king nor queen reigned;
* returns \\$0\\$ if a king was on the throne during the year (except Charles III (2022)); or
* returns \\$1\\$ otherwise (when a queen was on the throne the entire year, or 2022)

**Try it online!**

### How?

The byte-string `b'61/\n+|?4'` encodes the integers `[54,49,47,10,43,11,124,63,52]`. The `for` loop subtracts each from the year, `y`, cumulatively by employing the walrus operator, `:=`, and counts, with `sum(...)`, how many are less than `1500` (\\$54\\$ years before the first lone queen). To force an error for the sixth period (no monarch) and two distinct values otherwise arithmetic is employed:

| years | sum=N | 6-N | 9 mod (6-N) | (9 mod (6-N)) mod 2 | identifies |
| --- | --- | --- | --- | --- | --- |
| 927-1553 | 9 | -3 | 0 | 0 | king |
| 1554-1602 | 8 | -2 | -1 | 1 | queen |
| 1603-1649 | 7 | -1 | 0 | 0 | king |
| 1650-1659 | 6 | 0 | err | err | none |
| 1660-1702 | 5 | 1 | 0 | 0 | king |
| 1703-1713 | 4 | 2 | 1 | 1 | queen |
| 1714-1837 | 3 | 3 | 0 | 0 | king |
| 1738-1900 | 2 | 4 | 1 | 1 | queen |
| 1901-1953 | 1 | 5 | 4 | 0 | king |
| 1954-2022 | 0 | 6 | 3 | 1 | queen |

---

## Non-erroring alternative, 57 bytes

```
lambda y:2**sum((y:=y-v)<1500for v in b'61/\n+|?4')%40%3

```

Returns \\$2\\$ for King, \\$1\\$ for Queen, or \\$0\\$ for neither.

Try it online!

### How?

Same sum as before with different arithmetic:

| years | sum=N | 2\**N | (2\**N) mod 40 | ((2\**N) mod 40) mod 3 | identifies |
| --- | --- | --- | --- | --- | --- |
| 927-1553 | 9 | 512 | 32 | 2 | king |
| 1554-1602 | 8 | 256 | 16 | 1 | queen |
| 1603-1649 | 7 | 128 | 8 | 2 | king |
| 1650-1659 | 6 | 64 | 24 | 0 | none |
| 1660-1702 | 5 | 32 | 32 | 2 | king |
| 1703-1713 | 4 | 16 | 16 | 1 | queen |
| 1714-1837 | 3 | 8 | 8 | 2 | king |
| 1738-1900 | 2 | 4 | 4 | 1 | queen |
| 1901-1953 | 1 | 2 | 2 | 2 | king |
| 1954-2022 | 0 | 1 | 1 | 1 | queen |

# Answer
> 5 votes
# x86-64 machine code, ~~38~~ ~~32~~ 31 bytes

```
48 B9 64 12 33 20 9F A1 52 B8 31 C0 99 B6 06 88 EA 48 C1 C1 07 14 04 29 D7 99 79 F3 24 05 C3

```

Try it online!

Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes the year number in EDI and returns a value in EAX: 4 for kings, 0 for queens, and 1 for the interregnum.

In assembly:

```
f:
    mov rcx, 18<<8 | 50<<1 | 46<<58 | 10<<51 | 42<<44 | 12<<37 | 124<<30 | 64<<23 | 51<<16
                    # Put this constant in RCX.
    xor eax, eax    # Set EAX to 0.
    cdq             # Set EDX to 0 by sign-extending EAX.
    mov dh, 6       # Set the second-lowest byte of EDX to 6.
repeat:
    mov dl, ch      # Set the low byte of EDX to the second-lowest byte of RCX.
    rol rcx, 7      # Rotate RCX left by 7 bits.
    adc al, 4       # Add 4+CF to AL.
    sub edi, edx    # Subtract EDX from EDI.
    cdq             # Set EDX to 0 by sign-extending EAX.
    jns repeat      # Jump back to repeat if the subtraction's result is nonnegative.
    and al, 5       # Keep only the 1s bit and the 4s bit of AL.
    ret             # Return.

```

The basic way this works is to decrease the given number by 1554, 50, 46, 10, 42, 12, 124, 64, 51, 137, stopping when the result is negative, so that the loop executes a different number of times for each period of constant output.

The years of change were assigned to make all the period lengths even, except the last two. This allows the values to be stored in 7 bits each, so that nine can fit into a 64-bit register, while extracting 8 bits at a time (which includes the previous value's low bit) and still functioning correctly.

The 10th value extracted (for Elizabeth II's reign) entirely overlaps the 1st and 9th values, so we can only control its high bit, by assigning the year 1952. But because only years up to 2022 have to be handled, it is OK for this value to be higher than necessary.

The 1st value, which is 1554, is created by setting the second-lowest byte before the loop and then inserting the low byte within the loop (saving 2 bytes compared to pre-setting the whole thing).

To handle the interregnum, notice that the low bit of RCX ends up being 1 only when the given year is during the interregnum or the king period that follows it, and that is the same bit that gets copied into CF by the `ROL` instruction. An `ADC` instruction adds 4+CF to AL with each iteration, so that the 4s bit alternates between 0 and 1, while the 1s bit stays 0 initially, then becomes 1 for the interregnum and becomes 0 again for the next period, and stays 0 thereafter. At the end, an `AND` instruction picks out those two bits.

# Answer
> 4 votes
# Retina 0.8.2, ~~118~~ 117 bytes

```
165.
LP
155[4-9]|15[6-9].|160[0-2]|170[3-9]|171[0-3]|183[89]|18[4-9].|1900|195[3-9]|19[4-9].|20[01].|202[01]
Q
...+
K

```

Try it online! Link includes some test cases. Outputs `K` if there was ever a King in that year, otherwise `Q` if there was ever a Queen in that year, otherwise `LP`, as the Cromwells used the title "Lord Protector" for some of that period. Edit: Saved 1 byte thanks to @pxeger.

# Answer
> 4 votes
# Jelly,  ~~25 23~~  22 bytes

```
⁽£4;“1/½+¿|?4‘Ä<⁸SḂ⁻¡3

```

A monadic Link that accepts an integer in \\$\[927,2022\]\\$ and yields:

* \\$0\\$ if there was a king on the throne at any point during the year (except for Charles III (2022));
* \\$3\\$ if neither a king nor queen reigned; or
* \\$1\\$ otherwise (if a queen and only a queen reigned all year or Charles III succeeded (2022)).

**Try it online!** Or see all years.

### How?

```
⁽£4;“1/½+¿|?4‘Ä<⁸SḂ⁻¡3 - Link: integer, Y
⁽£4                    - 1553
    “1/½+¿|?4E‘        - code-page indices = [49,47,10,43,11,124,63,52]
   ;                   - concatenate -> [1553,49,47,10,43,11,124,63,52]
              Ä        - accumulate -> [1553,1602,1649,1659,1702,1713,1837,1900,1952]
               <⁸      - less than Y? (vectorises)
                 S     - sum -> S
                    ¡  - repeat...
                   ⁻ 3 - ...number of times: not equal to three
                                             (leave as 3 when no monarch)
                  Ḃ    - ...action: mod 2
                                    -> 0 if a king during the year except 2022; or
                                       1 otherwise

```

# Answer
> 2 votes
# Perl 5 `-Mutf8 -MList::Util=pairgrep -p`, 67 bytes

```
$_=/^165/?N:pairgrep{$a<$_&&$_<$b}unpack"U*","ؑكڙڞڦڲܭݭޠߦ"

```

Try it online!

Outputs `1` for a Queen, `0` for a King, or `N` for none.

# Answer
> 1 votes
# Zsh, 67 bytes

```
>$1<165?&&bye 2
< (1(<553-603>|6<89-94>|7<2-14>|<837-901>)|<1952->)

```

Attempt This Online!

Outputs via exit code: 0 for queen, 1 for king, and 2 for neither.

Explanation:

* `>$1`: create a file named according to the input
* `<165?`: search for a file beginning with `165` (as there was no monarch during that decade)
    + `&&bye 2`: if one exists, exit early with exit code 2
* `<`: otherwise, search for a file matching the long pattern of periods when there was a queen
    + `<x-y>` is a Zsh pattern searching for a number in the range \\$ \[x, y\] \\$
* Zsh will then exit with 1 if no file matches that pattern, and 0 otherwise

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

```
*p;f(y){for(p=L"2/\n+{@3,//";y>1552;)y-=*p++;y=2704%*p&3;}

```

Try it online!

-2 bytes thanks to ceilingcat!!

# Answer
> 0 votes
# Python 3, 131 bytes

```
a=[1553,1603,1689,1694,1702,1714,1837,1901,1952,2022]
f=lambda x:"AKQ"[any(i for i in range(5)if a[2*i]<x<a[2*i+1])*2or x//10!=165]

```

Try it online!

# Answer
> 0 votes
# Python 3, 120 bytes

```
r=lambda s,l:{*range(s,s+l)}
f=lambda y:2*(y in r(1650,10))+(y in r(1553,51)|r(1689,6)|r(1702,13)|r(1837,65)|r(1952,71))

```

Try it online!

Interpreting the output: 0 = King, 1 = Queen, 2 = Neither.

Nothing too fancy here. Commented version of `f`:

```
f=lambda y:(
  2

  # y in r(1650,10) = is neither king nor queen
  * (y in r(1650,10))

  # y in ... = is queen
  + (y in r(1553,51)|r(1689,6)|r(1702,13)|r(1837,65)|r(1952,71))
)

```

---
Tags: code-golf
---


# Question
Title: Number of ways to partition n into n = K + ꓘ
In this challenge you are asked to find in *how many ways* we can express a positive integer `n` as the sum of two positive integers `k` and the `reverse of k`.

Here is an example using `n = 1069` :
`188 + 881 = 1069`
`287 + 782 = 1069`
`386 + 683 = 1069`
`485 + 584 = 1069`
`980 + 89 = 1069`
So, the answer here would be `5`.

**rules**
As you can see we count every pair once: `{188,881}` is the same as `{881,188}`.
If a number cannot be expressed as such, your program should return `0`.
Your program should take as `input` a `positive integer` and return an `integer`.

**test cases**

```
1 -> 0
2 -> 1 (this is 1 + 1 = 2)
22 -> 2
101 -> 1 ( this is 100 + 001 = 100 + 1 = 101 )
132 -> 4
8547 -> 20
49886 -> 0
955548 -> 113
1100000 -> 450

```

This is `CodeGolf`! The shortest code in bytes, wins!

# Answer
> 8 votes
# Jelly, 9 bytes

```
rHDṚḌ+Ʋ€ċ

```

A monadic Link that accepts a positive integer and yields the number of valid pairs distinct up to reversing

**Try it online!**

### How?

```
rHDṚḌ+Ʋ€ċ - Link: positive integer, N
 H        - halve {N} -> N/2
r         - {N} inclusive range {that} -> [N, N-1, ..., floor(N/2)]
       €  - for each such "potential larger of the pair"*, X:
      Ʋ   -   last four links as a monad - f(X):
  D       -     convert {X} to decimal digits
   Ṛ      -     reverse
    Ḍ     -     convert from decimal digits
     +    -     add {X}
        ċ - count occurrences of {N}

```

* Note: while odd \\$N\\$ *do* include one "potential larger of the pair" that *would not be* the larger of the pair (\\$X=\lfloor \frac{N}{2} \rfloor\\$), that value can *never* work. This is because \\$N=\lfloor \frac{N}{2} \rfloor + \lceil \frac{N}{2} \rceil\\$ and so \\$\text{reverse}(X) - X = 1\\$ but this isn't a multiple of \\$9\\$. (Thanks to Neil for simplifying my explanation!)

# Answer
> 5 votes
# Vyxal 3 `s`, 7 bytes

```
½⌊z-ᵛṁ=

```

Try it Online!

Port of Jelly answer

-2 bytes thanks to @pacman256

```
½⌊z-ᵛṁ=
   -     ## n -
½⌊z      ## [0 .. floor(N / 2)]
    ᵛṁ   ## for every element n, n + mirror(n)
      =  ## equals to itself? (vectorized)
## The flag -s counts every Truthy values.

```

Created with the help of Luminespire.

# Answer
> 5 votes
# , 70 bytes

```
\(x)sum(sapply(x:(x/2),\(z)z%/%(b=10^(0:log10(z)))%%10%*%rev(b)+z)==x)

```

Attempt This Online!

More or less an R translation of @JonathanAllan’s Jelly answer, so be sure to upvote that one too!

# Answer
> 4 votes
# Pyth, 9 bytes

```
/ec2m+s_`

```

Try it online!

### Explanation

```
                 # implicitly assign Q = eval(input())
/ec2m+s_`ddQQ    # implicitly add ddQQ
    m      Q     # map lambda d over range(Q)
       _`d       #   reverse string(d)
      s          #   convert back to integer
     +    d      #   add d
  c2             # chop list into 2 parts of equal length
 e               # take the second part
/           Q    # count instances of Q

```

# Answer
> 3 votes
# Charcoal, ~~16~~ 15 bytes

```
ＮθＩΣＥ⮌…·⊘θθ⁼κ⮌ι

```

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

```
Ｎθ              First input as a number
      …·        Inclusive range from
         θ      Input number
        ⊘       Halved
          θ     To input number
     ⮌          Reversed
    Ｅ           Map over values
            κ   Current index
           ⁼    Equals
             ι  Current value
            ⮌   Reversed
   Σ            Take the sum
  Ｉ             Cast to string
                Implicitly print

```

Reversing the range means the value plus index always equals the input number, so we just need to check that the latter is the reverse of the former.

# Answer
> 2 votes
# Python 3, 56 bytes

```
lambda x:sum(i>=x-i==int(str(i)[::-1])for i in range(x))

```

Try it online!

or 53 bytes Python2 by Fmbalbuena

# JavaScript (Node.js), 59 bytes

```
x=>(g=t=>t&&g(t-1)+!([...x-t+''].reverse().join``^t))(x>>1)

```

Try it online!

-1 Byte from Arnauld

# Answer
> 2 votes
# APL (Dyalog Unicode), 40 35 bytes (SBCS)

```
{+/⍵=10⊥¨(⌽+⊢)¨10⊥⍣¯1¨¯1+(⌊⍵÷2)+⍳⍵}

```

Try it online!

37 **32** with `⎕IO←0`:

```
{+/⍵=10⊥¨(⌽+⊢)¨10⊥⍣¯1¨(⌊⍵÷2)+⍳⍵}

```

Try it online!

# Answer
> 2 votes
# Uiua SBCS, 19 bytes

```
/+=+⋕∵⇌°⋕.-+1⇡⌊÷2..

```

Try it!

```
/+=+⋕∵⇌°⋕.-+1⇡⌊÷2..
                 .. # duplicate input twice
              ⌊÷2   # halve and floor
             ⇡      # range
           +1       # increment
          -         # subtract from input
         .          # duplicate
       °⋕           # unparse (convert to array of boxed strings)
     ∵⇌             # reverse each
    ⋕               # convert all to integers
   +                # add reversed to non-reversed
  =                 # where is it equal to input?
/+                  # sum

```

# Answer
> 2 votes
# Ruby, 46 bytes

```
->x{(x/2..x).count{x==_1+_1.digits.join.to_i}}

```

Attempt This Online!

# Answer
> 2 votes
# 05AB1E, 7 bytes

```
;ŸDí+QO

```

Try it online or verify all test cases.

**Explanation:**

```
;        # Halve the (implicit) input-integer
 Ÿ       # Pop and push a list in the range [(implicit) input, floor(input/2)]
  D      # Duplicate this list
   í     # Reverse each inner value in the copy
    +    # Add the values at the same positions in the lists together
     Q   # Check for each whether it equals the (implicit) input
      O  # Sum the amount of truthy values
         # (which is output implicitly as result)

```

# Answer
> 1 votes
# Zsh, 48 bytes

```
for ((i=$1;i-->$1/2;c+=`rev<<<$i`+i==$1)):
<<<$c

```

Attempt This Online!

Terribly slow, because to reverse a string in Zsh you have to spawn a process!

# Answer
> 1 votes
# Perl 5, 48 bytes (30 bytes w/o args or return)

```
($x,$n)=(0,@_);$x+=$_+reverse==$n for$n/2..$n;$x

```

Try it online!

# Answer
> 1 votes
# Desmos, 80 bytes

```
f(k)=∑_{n=.5k}^k0^{(k-n-∑_{d=0}^n10^{floor(logn)-d}mod(floor(n/10^d),10))^2}

```

Try It On Desmos!

Try It On Desmos! - Prettified

# Answer
> 1 votes
# Scala 3, 53 bytes

```
x=>(x/2 to x).count{i=>i+i.toString.reverse.toInt==x}

```

Attempt This Online!

---
Tags: code-golf, arithmetic
---


title: sum of a range of a sum of a range of n

text:
# Question
Title: sum of a range of a sum of a range of n
In this challenge, your input is an integer value. Your task is to find the sum of the range of the sum of the range of n.

Examples:

```
Input -> Output
1     -> 1
2     -> 6
3     -> 21
4     -> 55
5     -> 120
6     -> 231
7     -> 406
8     -> 666
9     -> 1035
10    -> 1540

```

This challenge should be fairly simple to complete in most languages :)
Have fun!

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

```
x=>(x*x-~x)**2>>3

```

Try it online!

Thanks Kevin Cruijssen for -1 byte.
> 12 votes

# Answer
# C (gcc), 22 bytes

*With unsequenced modification and access to `n`*

```
f(n){n*=~n;n=--n*n/8;}

```

Try it online!

# C (clang), 26 bytes

*With unsequenced modification and access to `n`*

```
f(n){n*=~n;return--n*n/8;}

```

Try it online!

# C89, 28 bytes

```
f(n){n*=~n;return(n-2)*n/8;}

```

Try it online!

## Explanation

```
f(n){n*=~n;return--n*n/8;}  // function which takes and returns an integer
     n*=~n;                 // n *= -(n + 1); here (n = -(n*n + n))
                 --n        // decrement n;   here (n = -(n*n + n + 1))
           return  n*n/8;   // return (n*n + n + 1)^2 / 8

```
> 11 votes

# Answer
# Wolfram Language (Mathematica), 15 bytes

```
#@*#&@Tr@*Range

```

Try it online!

-1 byte from @att

# Wolfram Language (Mathematica), 16 bytes

```
(f=Tr@*Range)@*f

```

Try it online!
> 10 votes

# Answer
# APL (Dyalog Unicode), 6 bytes

Anonymous tacit prefix function.

```
+/∘⍳⍣2

```

Try it online!

`+/` the sum

of

the range

`⍣2` twice
> 9 votes

# Answer
# Japt `-x`, 5 bytes

```
õ x õ

```

Try it
> 7 votes

# Answer
# Haskell, 17 bytes

```
g.g
g n=sum[1..n]

```

Try it online!

Just implementing the definition seems to be shorter than arithmetical expressions such as

**21 bytes**

```
f n=((n^2+n+1)^2-1)/8

```

Try it online!

With floats:

**17 bytes**

```
g.g
g n=n*(n+1)/2

```

Try it online!
> 6 votes

# Answer
# Brain-Flak, 32 bytes

```
({({}[()])()}{})
({({}[()])()}{})

```

Try it online!

(The newline isn't needed, but is included because it makes the answer pretty)

Polygonal numbers are one of the things that brain-flak uniquely excels at. This is just the code that calculates the N-th triangular number, repeated twice.

```
# Push (the sum of...)
(
    # While the top of stack is not 0...
    {
        # Decrement the top of the stack by 1
        # This adds n-1 to the running counter
        ({}[()])

        # Plus 1 (to the running counter)
        ()
    }

    # Pop the stack (which should contain a 0 now)
    {}
)

```
> 6 votes

# Answer
# Nibbles, 2 bytes (4 nibbles)

```
+,+,

```

Attempt This Online!

### Explanation

```
+,+,$
    $  Input number (implicit)
   ,   Range from 1 to that number
  +    Sum
 ,     Range from 1 to that number
+      Sum

```
> 5 votes

# Answer
# Binary Lambda Calculus, 125 bits = 15.625 bytes

```
01000001 11001110 10000101 01100001 10010000 00000101 10011111 01110010
11110111 10110000 00001110 01011110 11010000 10110001 00000100 00010

```

Verify it online!

Encodes the following lambda term:

```
main = 2 rangesum where
  succ = \n f x. f (n f x)
  pair = \x y f. f x y
  snd = \p. p (\x y. y)
  update = \p. p (\x y f. f (succ x) (x succ y))
  rangesum = \n. snd (n update (pair 1 0))

```

This is a function that takes a positive integer in Church numeral and outputs the answer in the same form. The numbers that appear in the Haskell-like code above are also Church numerals, e.g. `2 = \f x. f (f x)`.
> 5 votes

# Answer
# Charcoal, 10 bytes

```
Ｉ÷⍘12320Ｎ⁸

```

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

```
   12320    Literal string `12320`
  ⍘         Interpret as base
        Ｎ   First input as a number
 ÷          Integer divide by
         ⁸  Literal integer `8`
Ｉ           Cast to string
            Implicitly print

```

The boring solution is 8 bytes:

```
ＩΣ…·Σ…·Ｎ

```

Try it online! Link is to verbose version of code. Explanation: `InclusiveRange` prefers two arguments, but fortunately we can arrange to use the one-argument version (twice, saving two bytes).

```
       Ｎ    First input as a number
     …·     Inclusive range from `1` to that
    Σ       Take the sum
  …·        Inclusive range from `1` to that
 Σ          Take the sum
Ｉ           Cast to string
            Implcitly print

```
> 4 votes

# Answer
# 05AB1E, 4 bytes

```
LOLO

```

Try it online or verify all test cases.

**Explanation:**

```
L     # Push a list in the range [1, (implicit) input-integer]
 O    # Sum this list together
  L   # Pop and push a list in the range [1, sum]
   O  # Sum this list together again
      # (after which the result is output implicitly)

```

Laughing Out Loud! Out??

An equal-bytes alternative could be: `2FLO`, where `2F` is loop 2 times:
Try it online or verify all test cases.
> 4 votes

# Answer
# Vyxal, 4 bytes

```
ɾ∑ɾ∑

```

Try it Online!

Uses the straightforward approach: `ɾ` gets the range from 1 through its argument, and  sums. Rinse and repeat.
> 4 votes

# Answer
# Desmos, ~~21~~ 20 bytes

```
N=nn+n
f(n)=N(N+2)/8

```

Try It On Desmos!
> 4 votes

# Answer
# , 19 bytes

```
\(n)sum(1:sum(1:n))

```

Attempt This Online!
> 4 votes

# Answer
# Pyth, 4 bytes

```
sSsS

```

Try it online!

### Explanation

```
sSsSQ    # implicitly add Q
         # implicitly assign Q = eval(input())
   SQ    # range 1 to Q
  s      # sum
 S       # range 1 to result
s        # sum

```

Extra nice since when pronounced out loud it is the sound a python makes.
> 4 votes

# Answer
# brainf\**k, 110 bytes

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

```

Try it online!

Probably not the shortest implementation but I'm too lazy to make this shorter lol...

Like most other b\****fuck programs, it doesn't output the answer. Instead, it prints the ascii character corresponding to the numeric answer.

Check this out to see the running process.
> 4 votes

# Answer
# PARI/GP, 16 bytes

-2 byte thanks to @tsh.

```
n->(1+n^2+n)^2\8

```

Attempt This Online!
> 3 votes

# Answer
# Python, 23 bytes

-7 bytes thanks to `c--`'s suggestion based on `tsh`'s answer.

```
lambda n:(n*n-~n)**2//8

```

Attempt This Online!

# Python, 38 bytes

```
lambda n:sum(range(sum(range(n+1))+1))

```

Attempt This Online!
> 3 votes

# Answer
# Java, ~~18~~ 17 bytes

```
n->(n=n*n-~n)*n/8

```

Port of *@tsh*' JavaScript answer, so make sure to upvote him/her as well.
-1 byte thanks to *@tsh*.

Try it online.

`(n=n*n-~n)` could alternatively be `(n+=n*n+1)` for the same byte-count:
Try it online.

**Explanation:**

```
n->               // Method with integer as both parameter and return-type
  (n=             //  Replace `n` with:
     n*n          //   `n` squared
        -~n)      //   `+n+1`
            *n    //  Square that new `n`
              /8  //  Integer-divide that by 8 to get the result

```

---

A literal implementation would be **56 bytes** in comparison:

```
n->{int t=0;for(;n>0;)t+=n--;for(;t>0;)n+=t--;return n;}

```

Try it online.

**Explanation:**

```
n->{          // Method with integer as both parameter and return-type
  int t=0;    //  Temp-integer, starting at 0
  for(;n>0;)  //  Loop `n` down until it's 0:
    t+=n      //   Add the current `n` to the temp-integer `t`
        --;   //   And then decrease `n` by 1
              //  (at this point, `n=0`)
  for(;t>0;)  //  Now loop `t` down until it's 0:
    n+=t      //   Add the current `t` to `n`
        --;   //   And then decrease `t` by 1
  return n;}  //  Return the modified `n` as result

```
> 3 votes

# Answer
# Go, ~~41~~ 37 bytes

```
func(n int)int{n=n*n-^n
return n*n/8}

```

Attempt This Online!

* -4 bytes by @c--
> 3 votes

# Answer
# Haskell, 21 bytes

```
t n=sum[1..sum[1..n]]

```

Try it online!
> 3 votes

# Answer
# x86-16 machine code, 13 bytes

```
00000000: 8ad8 43f6 e340 f7e0 b103 d3e8 c3         ..C..@.......

```

Listing:

```
8A D8       MOV   BL, AL        ; BL = x
43          INC   BX            ; BL = x + 1
F6 E3       MUL   BL            ; AX = x * (x + 1)
40          INC   AX            ; AX = x * (x + 1) + 1
F7 E0       MUL   AX            ; AX = AX * AX
B1 03       MOV   CL, 3
D3 E8       SHR   AX, CL        ; AX = AX >> 3
C3          RET                 ; return to caller

```

Callable with input `n` in `AL`, output in `AX`.

Uses the formula `(x*(x+1)+1)^2>>3`.
> 3 votes

# Answer
# Julia, 16 bytes

```
!n=(n^2-~n)^2÷8

```

Attempt This Online!

The formula looks a bit shorter than directly writing out the sums.
> 3 votes

# Answer
# Arturo, 18 bytes

```
$=>[∑1..∑1..&]

```

Try it!
> 3 votes

# Answer
# Factor \+ `math.unicode`, 21 bytes

```
[ [1,b] Σ [1,b] Σ ]

```

Try it online!
> 3 votes

# Answer
# Husk, 2 bytes

```
‼Σ

```

Try it online!

```
‼         # Apply function twice:
Σ         # Triangular number

```

(the more-boring `ΣΣ` is also 2 bytes...)
> 3 votes

# Answer
# C, 65 bytes

`f(n){int i=10;for(;i>1;)n+=i--;for(;n>1;)i+=n--;printf("%d",i);}`

## Earlier attempts

### 73 bytes

`main(){int i=0,n=10;for(;n>0;)i+=n--;for(;i>0;)n+=i--;printf("%d\n",n);}`

### 70 bytes

`main(n){int i=10;for(;i>1;)n+=i--;for(;n>1;)i+=n--;printf("%d\n",i);}`
> 2 votes

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

* -2 bytes thanks to Bubbler

```
i:1+*2,:1+*2,n;

```

Try it

Just the triangle number formula copied twice
> 2 votes

# Answer
# Thunno 2, 4 bytes

```
RSRS

```

Attempt This Online!

Range, sum, range, sum.
> 2 votes

# Answer
# Rockstar, ~~68~~ 54 bytes

```
listen to N
cast N
let N be*N+1
let X be N+2
say N*X/8

```

Try it here (Code will need to be pasted in)

Saved 12 byes thanks to c--'s suggestion to use a different formula.
> 2 votes

# Answer
# Lua, 24 bytes

```
print((...^2-~...)^2//8)

```

Try it online!

Based off tsh's answer, though it's been modified a bit to better fit Lua.
> 2 votes

# Answer
# BQN, ~~9~~ 6 bytes

*-3 bytes thanks to att*

```
+´⟜↕⍟2

```

Anonymous tacit function that takes a number and returns a number. Try it at BQN online!

### Explanation

Same idea as Adám's APL answer, slightly complicated by the fact that BQN's ranges are 0-based.

Call the argument N:

```
+´⟜↕⍟2
   ↕     Range (0 to N-1)
+´       Fold on addition...
  ⟜     ... with a starting value of N
    ⍟2  Apply that function twice

```
> 2 votes

# Answer
# Retina 0.8.2, 19 bytes

```
.+
$*
1
1$`
1
1$`
1

```

Try it online! Link includes test cases. Explanation:

```
.+
$*

```

Convert to unary.

```
1
1$`

```

Sum of range.

```
1
1$`

```

Sum of range.

```
1

```

Convert to decimal.
> 2 votes

# Answer
# Jelly, 4 bytes

```
RSRS

```

Attempt This Online!

Nobody golfing in Jelly anymore?
> 2 votes

# Answer
# Pyt, 2 bytes

```
△△

```

Try it online!

Uses the built-in for triangle number twice. Implicit input and output.
> 2 votes

# Answer
# K (ngn/k), 9 bytes

```
2{x+/!x}/

```

Try it online!

* `2{...}/` set up a monadic do-reduce, running the code in `{...}` twice
    + `!x` generate `0..x-1`
    + `x+/` set up a plus-reduce (i.e. sum) seeded with the input `x`
> 2 votes

# Answer
# Excel, ~~26~~ 24 bytes

```
=A1*(A1+1)/8*(A1^2+A1+2)

```

Input in cell `A1`.
> 1 votes

# Answer
# Ly, 6 bytes

```
R&+R&+

```

Try it online!

A pretty direct mapping of the rules of the contest to Ly instructions for this one...

```
R      - Generate range of numbers from 0 to STDIN
 &+    - Sum the stack
   R   - Generate range of numbers again, from 0 to top-of-stack
    &+ - Sum the stack
       - Top of stack printed as a number be default on exit

```
> 1 votes

# Answer
# MathGolf, 4 bytes

```
╒Σ╒Σ

```

Try it online.

**Explanation:**

```
╒     # Push a list in the range [1, (implicit) input-integer]
 Σ    # Sum it together
  ╒   # Pop and push a list in the range [1, sum]
   Σ  # Sum it together again
      # (after which the entire stack is output implicitly as result)

```
> 1 votes

# Answer
# PHP, 25 bytes

```
fn($n)=>($n**2-~$n)**2>>3

```

Attempt This Online!
> 1 votes

# Answer
# Trilangle, 15 bytes

```
?22)d**2'd')2p@

```

Try it on the online interpreter!

Just the code for "sum range" twice.
> 1 votes

# Answer
# SAS 4GL, 22 ~~23~~ bytes

The code:

```
o=n*(n+1)*(n*n+n+2)/8;

```

The code plus "environment" and nice printout:

```
data;
  do n = 1 to 10;
    o=n*(n+1)*(n*n+n+2)/8;
    put n "-> " o;
  end;
run;

```

The log:

```
1    data;
2      do n = 1 to 10;
3        o=n*(n+1)*(n*n+n+2)/8;
4        put n "-> " o;
5      end;
6    run;

1 -> 1
2 -> 6
3 -> 21
4 -> 55
5 -> 120
6 -> 231
7 -> 406
8 -> 666
9 -> 1035
10 -> 1540
NOTE: The data set WORK.DATA4 has 1 observations and 2 variables.
NOTE: DATA statement used (Total process time):
      real time           0.01 seconds
      cpu time            0.01 seconds

```
> 1 votes

# Answer
# Nim, 36 bytes

```
func a[I](n:I):I=(n*n+n)*(n*n+n+2)/8

```

Attempt This Online!

Takes and returns a float (so I can use `/` instead of `div`).
> 1 votes

# Answer
# SAS IML, 18 bytes

The code:

```
o=sum(1:sum(1:n));

```

The code plus "environment" and nice printout:

```
proc IML;
  do n= 1 to 10;
    o=sum(1:sum(1:n));
    print n " => " o;
  end;
quit;

```

The log:

```
1    proc IML;
NOTE: IML Ready
2      do n= 1 to 10;
3        o=sum(1:sum(1:n));
4        print n " => " o;
5      end;
6    quit;
NOTE: Exiting IML.
NOTE: PROCEDURE IML used (Total process time):
      real time           0.01 seconds
      cpu time            0.01 seconds

```

Output:

Acknowledgement:

Thank you to Mr. Roman Czyborra for the Haskel inspiration!
> 1 votes

# Answer
# minigolf, 7 bytes

```
2,,n;+_

```

Try it online!

## Explanation

```
2,    _  Repeat 2 times:
  ,n;    Generate a [1..n] range
     +   Sum it

Implicit output

```
> 1 votes

# Answer
# ARBLE, 13 bytes

```
(n^2-~n)^2//8

```

Direct port of bluswimmer's port of tsh's answer, utilising ARBLE's more terse extensions.

Try it online!
> 1 votes

# Answer
# AWK, 23 bytes

```
$0=int((1+$0^2+$0)^2/8)

```

Try it online!

---

This will also work if the input is 0 (~~28~~ thank to @Dominic van Essen 24 bytes):

```
$0=int((1+$0^2+$0)^2/8)a

```
> 1 votes

# Answer
# Bash/Zsh, 19 bytes

```
$[($1**2-~$1)**2/8]

```

Try it online!
> 1 votes

# Answer
# K (ngn/k), 15 bytes

```
-8!*/0 2+*/0 1+

```

Try it online!
> 1 votes

# Answer
# Ruby, 26 bytes

The following is probably the most direct approach to the problem given Ruby's basic methods.

```
->(n){(1..(1..n).sum).sum}

```

Try it online!

***Another idea:*** Let *T(n)* be the *n*-th triangular number. Our answer is *T(T(n))* \- we're interested in the *T(n)*-th triangular number.
> 1 votes

# Answer
# AWK, 21 bytes

```
$0*=$0+1,$0*=($0+2)/8

```

Attempt This Online!

Given a positive integer as input, the following happens in sequence:

* The pattern `$0*=$0+1` is tested. `$0` initially contains the input number `n`, and is overwritten to `n^2+n`. Since this is nonzero, the pattern is matched, and a "range match" starts.
* The pattern `$0*=($0+2)/8` is tested. `$0` is overwritten to `(n^2+n)(n^2+n+2)/8`. Since this is nonzero, the pattern is also matched, and the "range match" ends immediately.
* The default action is performed, which is to print `$0`.
> 1 votes

# Answer
# Neim, 4 bytes

```

```

Explanation:

```
     # inclusive range
     # sum range
     # inclusive range
     # sum range

```

Try it online!
> 0 votes

# Answer
# Scala, 25 bytes

Saved 1 byte(s) thanks to the comment of @Jo King ♦

---

What's it?

Accroding to A002817, doubly triangular numbers are revealed in the sums of row sums of Floyd's triangle.

```
1, 1+5, 1+5+15, ...
             1
          2     3
       4     5     6
    7     8     9     10
11    12    13    14    15

```

---

Golfed version. Try it online!

```
n=>(1 to(1 to n).sum).sum

```

Ungolfed version. Try it online!

```
object Main {
  def main(args: Array[String]): Unit = {
    def t(n: Int): Int = (1 to (1 to n).sum).sum
    println((0 to 9).map(t).map(_.toString).mkString(" "))
  }
}

```
> 0 votes

# Answer
# J-uby, 12 bytes

```
(:+|:sum)**2

```

Attempt This Online!
> 0 votes

# Answer
# AArch64 machine code, 20 bytes

```
00: 9b000000  madd x0, x0, x0, x0 // x = x * x + x
04: d341fc00  lsr x0, x0, #1      // x = x / 2
08: 9b000000  madd x0, x0, x0, x0 // x = x * x + x
0c: d341fc00  lsr x0, x0, #1      // x = x / 2
10: d65f03c0  ret

```

simple :)

use it as a function `uint64_t f(uint64_t x)`. will overflow on inputs \> 92681.

you could also use it as `main` (not `_start` unless you replace the `ret` with an `exit` syscall) and its input will be the argument count including the program name.
> 0 votes

# Answer
# Moonscript/Yuescript, 18 bytes

```
(n)->(n^2-~n)^2//8

```

Try it online!
> 0 votes

# Answer
# Racket \+ `math`, 38 bytes

```
(sum(range(+(sum(range(+(read)1)))1)))

```

Try it online!

Although it's verbose and a bit slow, it's shorter than placing in the actual equation and/or using `apply +` instead of `sum`, and it doesn't cheat by using `triangle-number`:

* 43 bytes + faster

```
((λ(f)(f(f(read))))(λ(n)(/(*(+ n 1)n)2)))

```

Try it online!
* 46 bytes, no `math` import

```
(apply +(range(+(apply +(range(+(read)1)))1)))

```

Try it online!
* 36 bytes, using `triangle-number` from `math`, it's fast and -2 bytes, but might be somewhat cheating?

```
((λ(t)(t(t(read))))triangle-number)

```

Try it online!
> 0 votes

# Answer
# Uiua SBCS, 9 bytes

```
⍥(/++1⇡)2

```

Try it!
> 0 votes

# Answer
# Perl 5 `-MList::Util=sum -p`, 19 bytes

```
$_=sum 1..sum 1..$_

```

Try it online!
> 0 votes

# Answer
# Vyxal `Rss`, 0 bytes

```

```

Try it Online!

That's right - with the power of subscription models, this task can be done in 0 bytes!

*but how does Really Simple Syndication help you sum a range twice?*

Well technically speaking it doesn't - of course there's no rss feed involved. What's happening is that the `R` flag coerces numbers to ranges when an iterable is needed, and the two `s` flags sum the top of the stack at the end of execution. Due to the way the flag handler is implemented, duplicate flags apply the flag effect multiple times.
> -1 votes

---
Tags: code-golf
---