# Question
Title: Simple encryption for people on a byte budget
## Overview

Your goal is to implement RC4 encryption. RC4 encryption, invented by Ron Rivest (of RSA fame), was designed to be secure, yet simple enough to be implemented from memory by military soldiers on the battlefield. Today, there are several attacks on RC4, but it's still used in many places today.

Your program should accept a single string with both a key and some data. It will be presented in this format.

```
\x0Dthis is a keythis is some data to encrypt

```

The first byte represents how long the key is. It can be assumed the key will no longer than 255 bytes, and no shorter than 1 byte. The data can be arbitrarily long.

Your program should process the key, then return the encrypted data. RC4 encryption and decryption are identical, so using the same key to "encrypt" the ciphertext should return the original plaintext.

## How RC4 Works

### Initialization

Initialization of RC4 is quite simple. A state array of 256 bytes is initialized to all bytes from 0 to 255.

```
S = [0, 1, 2, 3, ..., 253, 254, 255]

```

### Key processing

Values in the state are swapped around based on the key.

```
j = 0
for i from 0 to 255
    j = (j + S[i] + key[i mod keylength]) mod 256
    swap S[i] and S[j]

```

### Encryption

Encryption is accomplished by using the state to generate pseudo-random bytes, which are then XOR'd to the data. Values in the state are swapped around constantly.

```
i = j = 0
for each byte B in data
    i = (i + 1) mod 256
    j = (j + S[i]) mod 256
    swap S[i] and S[j]
    K = S[(S[i] + S[j]) mod 256]
    output K XOR B

```

## Expected inputs and outputs

Non-printable characters will be shown in `\xAB` format.

Input: `\x01\x00\x00\x00\x00\x00\x00`
Output: `\xde\x18\x89A\xa3`
Output(hex): `de188941a3`

Input: `\x0Dthis is a keythis is some data to encrypt`
Output: `\xb5\xdb?i\x1f\x92\x96\x96e!\xf3\xae(!\xf3\xeaC\xd4\x9fS\xbd?d\x82\x84{\xcdN`
Output(hex): `b5db3f691f9296966521f3ae2821f3ea43d49f53bd3f6482847bcd4e`

Input: `\x0dthis is a key\xb5\xdb?i\x1f\x92\x96\x96e!\xf3\xae(!\xf3\xeaC\xd4\x9fS\xbd?d\x82\x84{\xcdN`
Input(hex): `0d746869732069732061206b6579b5db3f691f9296966521f3ae2821f3ea43d49f53bd3f6482847bcd4e`
Output: `this is some data to encrypt`

Input: `Sthis is a rather long key because the value of S is 83 so the key length must matchand this is the data to be encrypted`
Output: `\x96\x1f,\x8f\xa3%\x9b\xa3f[mk\xdf\xbc\xac\x8b\x8e\xfa\xfe\x96B=!\xfc;\x13`c\x16q\x04\x11\xd8\x86\xee\x07`
Output(hex): `961f2c8fa3259ba3665b6d6bdfbcac8b8efafe96423d21fc3b13606316710411d886ee07`

# Answer
> 3 votes
## JavaScript (ES6), ~~169~~ 168 bytes

Takes input as an array of bytes. Returns another array of bytes.

```
([l,...s])=>s.slice(l).map(b=>b^S[(S[S[J=J+(t=S[I=I+1&m])&m,I]=x=S[J],J]=t)+x&m],[...S=[...Array(m=255).keys(),m]].map(i=>S[S[i]=S[j=j+(t=S[i])+s[i%l]&m],j]=t,I=J=j=0))

```

### How?

This is essentially a literal implementation of the spec.

We first split the input array into ***l*** (length of key) and ***s*** (payload data: key + message). Then, in order of execution:

* We initialize the state array ***S*** and define ***m = 255*** which is repeatedly used later as a bit mask.

```
S = [...Array(m = 255).keys(), m]

```
* We shuffle the state array. The indices ***I*** and ***J*** which are initialized here are actually used in the next step.

```
[...S].map(i =>
  S[S[i] = S[j = j + (t = S[i]) + s[i % l] & m], j] = t,
  I = J = j = 0
)

```
* We apply the encryption.

```
s.slice(l).map(b =>
  b ^ S[
    (S[S[J = J + (t = S[I = I + 1 & m]) & m, I] = x = S[J], J] = t) +
    x & m
  ]
)

```

### Test cases

```
let f =

([l,...s])=>s.slice(l).map(b=>b^S[(S[S[J=J+(t=S[I=I+1&m])&m,I]=x=S[J],J]=t)+x&m],[...S=[...Array(m=255).keys(),m]].map(i=>S[S[i]=S[j=j+(t=S[i])+s[i%l]&m],j]=t,I=J=j=0))

let toArray = s => [...s].map(c => c.charCodeAt())
let toHexa  = s => [...s].map(c => ('0' + c.toString(16)).slice(-2)).join` `

console.log(toHexa(f(toArray("\x01\x00\x00\x00\x00\x00\x00"))))
console.log(toHexa(f(toArray("\x0Dthis is a keythis is some data to encrypt"))))
console.log(String.fromCharCode(...f(toArray("\x0dthis is a key\xb5\xdb?i\x1f\x92\x96\x96e!\xf3\xae(!\xf3\xeaC\xd4\x9fS\xbd?d\x82\x84{\xcdN"))))
console.log(toHexa(f(toArray("Sthis is a rather long key because the value of S is 83 so the key length must matchand this is the data to be encrypted"))))
```

# Answer
> 16 votes
# 138 bytes, machine code (16-bit x86)

```
000000 88 9f 00 02 fe c3 75 f8 b9 01 00 89 fa b4 3f cd
000010 21 86 0d ba 00 03 b4 3f cd 21 89 dd 01 f6 02 9e
000020 00 03 8a 04 00 c3 86 87 00 02 88 04 46 45 39 cd
000030 75 02 31 ed 81 fe 00 03 75 e4 81 ee 00 01 31 db
000040 31 d2 ff c6 81 fe 00 03 75 04 81 ee 00 01 8a 04
000050 00 c3 88 c2 86 87 00 02 88 04 00 c2 89 d7 81 c7
000060 00 02 8a 15 89 d7 89 dd 31 db ba 00 03 b9 01 00
000070 b8 00 3f cd 21 87 fa 30 15 85 c0 74 0b 87 fa 43
000080 b4 40 cd 21 89 eb eb b8 cd 20

```

Running: save to codegolf.com, dosbox:

`codegolf.com < input.bin`

I don't know if this gonna count as an entry, but I've decided to do it **manually** using hex editors. **No compilers** were used to do this.

ht editor actually has assembler, but honestly I did not know about this until I was finished ¯\*(ツ)*

## Why & how

Why: mostly cause I wanted to check if I'm able to do this.

How: I've started with creating byte filled with `NOP`s and following with a simple part: trying to write first loop that fills `S`tate with 0..255 values. I switched to python and quickly wrote python version, just to have something to test against. Next I was simplifying python code into pseudo code / pseudo assembly. Then I I was trying to write small pieces. I decided it'll be easiest to read from stdin, so I started with something small that will read single byte, then I added password reading and key initialization. Figuring out what registers to pick took me some time.

I though adding de/encryption loop will be easy, but first I actually got single byte decode and added whole loop afterwards.

Last step was getting rid of additional `nops` that I've left between instructions when writing it (ofc that required fixing jumps as well).

You can see small gallery that I tried to make while progressing here.

## Dissection

The program relies on some initial values after startup (see resources below).

```
00000000 889f0002                  mov         [bx+0200], bl
00000004 fec3                      inc         bl
00000006 75f8                      jnz         0x0

```

fill in State (at 0x200)

```
00000008 b90100                    mov         cx, 0x1
0000000b 89fa                      mov         dx, di
0000000d b43f                      mov         ah, 0x3f
0000000f cd21                      int         0x21
00000011 860d                      xchg        [di], cl
00000013 ba0003                    mov         dx, 0300
00000016 b43f                      mov         ah, 0x3f
00000018 cd21                      int         0x21

```

read length, read password, store password at ds:0x300

```
0000001a 89dd                      mov         bp, bx
0000001c 01f6                      add         si, si
0000001e 029e0003                  add         bl, [bp+0300]
00000022 8a04                      mov         al, [si]
00000024 00c3                      add         bl, al
00000026 86870002                  xchg        [bx+0200], al
0000002a 8804                      mov         [si], al
0000002c 46                        inc         si
0000002d 45                        inc         bp
0000002e 39cd                      cmp         bp, cx
00000030 7502                      jnz         0x34
00000032 31ed                      xor         bp, bp
00000034 81fe0003                  cmp         si, 0300
00000038 75e4                      jnz         0x1e

```

initialize State with a key (`BP` is used to traverse key, `SI` is used to traverse State)

```
0000003a 81ee0001                  sub         si, 0100
0000003e 31db                      xor         bx, bx
00000040 31d2                      xor         dx, dx
00000042 ffc6                      inc         si
00000044 81fe0003                  cmp         si, 0300
00000048 7504                      jnz         0x4e
0000004a 81ee0001                  sub         si, 0100
0000004e 8a04                      mov         al, [si]
00000050 00c3                      add         bl, al
00000052 88c2                      mov         dl, al
00000054 86870002                  xchg        [bx+0200], al
00000058 8804                      mov         [si], al
0000005a 00c2                      add         dl, al
0000005c 89d7                      mov         di, dx
0000005e 81c70002                  add         di, 0200
00000062 8a15                      mov         dl, [di]

```

generate pseudo random value (in `DL`, `DH` is 0 thx to xor at 0x140)

```
00000064 89d7                      mov         di, dx
00000066 89dd                      mov         bp, bx
00000068 31db                      xor         bx, bx
0000006a ba0003                    mov         dx, 0300
0000006d b90100                    mov         cx, 0x1
00000070 b8003f                    mov         ax, 3f00
00000073 cd21                      int         0x21
00000075 87fa                      xchg        dx, di
00000077 3015                      xor         [di], dl
00000079 85c0                      test        ax, ax
0000007b 740b                      jz          0x88
0000007d 87fa                      xchg        dx, di
0000007f 43                        inc         bx
00000080 b440                      mov         ah, 0x40
00000082 cd21                      int         0x21
00000084 89eb                      mov         bx, bp
00000086 ebb8                      jmp         0x40
00000088 cd20                      int         0x20

```
* store values that we need to preserve (`SI` \- ints won't touch it, `BX`)
* read char from input, xor it
* quit if end of stream
* output decoded char
* restore values
* loop to 0x40 (reuse xor on `DX`)

P.S. This probably could be even shorter, but this took 4 evenings, so not sure if I want to spend another one...

## Tools and resources

# Answer
> 4 votes
# C (gcc), ~~193 188 182 178 171~~ 172 bytes

```
f(x,l)int*x;{unsigned char*X=x,i=0,j=0,S[256],t;for(;S[i]=++i;);for(;t=S[i],S[i]=S[j+=t+X[1+i%*X]],S[j]=t,t=++i;);for(X+=*X;l--;S[i]-=S[t]=j)*++X^=S[S[i]+=S[t+=j=S[++i]]];}

```

Try it online!

Edit: Now works with keys longer than 127 bytes.

Edit2: Added testcase with 129 byte key to TIO link.

Slightly less golfed version

```
f(x,l)int*x;{
  unsigned char*X=x,i=0,j=0,S[256],t;
  // initialize state
  for(;S[i]=++i;);
  // key processing
  for(;t=S[i],S[i]=S[j+=t+X[1+i%*X]],S[j]=t,t=++i;);
  // encrypt
  for(X+=*X;l--;S[i]-=S[t]=j)
    *++X^=S[S[i]+=S[t+=j=S[++i]]];
}

```

# Answer
> 4 votes
# CPU x86 instruction set, 133 bytes

```
000009F8  53                push ebx
000009F9  56                push esi
000009FA  57                push edi
000009FB  55                push ebp
000009FC  55                push ebp
000009FD  BF00010000        mov edi,0x100
00000A02  29FC              sub esp,edi
00000A04  8B6C3C18          mov ebp,[esp+edi+0x18]
00000A08  31DB              xor ebx,ebx
00000A0A  8A5D00            mov bl,[ebp+0x0]
00000A0D  45                inc ebp
00000A0E  31C0              xor eax,eax
00000A10  880404            mov [esp+eax],al
00000A13  40                inc eax
00000A14  39F8              cmp eax,edi
00000A16  72F8              jc 0xa10
00000A18  31F6              xor esi,esi
00000A1A  31C9              xor ecx,ecx
00000A1C  89F0              mov eax,esi
00000A1E  31D2              xor edx,edx
00000A20  F7F3              div ebx
00000A22  8A0434            mov al,[esp+esi]
00000A25  02441500          add al,[ebp+edx+0x0]
00000A29  00C1              add cl,al
00000A2B  8A0434            mov al,[esp+esi]
00000A2E  8A140C            mov dl,[esp+ecx]
00000A31  88040C            mov [esp+ecx],al
00000A34  881434            mov [esp+esi],dl
00000A37  46                inc esi
00000A38  39FE              cmp esi,edi
00000A3A  72E0              jc 0xa1c
00000A3C  8B443C1C          mov eax,[esp+edi+0x1c]
00000A40  01E8              add eax,ebp
00000A42  722F              jc 0xa73
00000A44  48                dec eax
00000A45  89C6              mov esi,eax
00000A47  01DD              add ebp,ebx
00000A49  31C0              xor eax,eax
00000A4B  31D2              xor edx,edx
00000A4D  31C9              xor ecx,ecx
00000A4F  39F5              cmp ebp,esi
00000A51  7320              jnc 0xa73
00000A53  FEC2              inc dl
00000A55  8A0414            mov al,[esp+edx]
00000A58  00C1              add cl,al
00000A5A  8A1C0C            mov bl,[esp+ecx]
00000A5D  88040C            mov [esp+ecx],al
00000A60  881C14            mov [esp+edx],bl
00000A63  00D8              add al,bl
00000A65  8A1C04            mov bl,[esp+eax]
00000A68  8A4500            mov al,[ebp+0x0]
00000A6B  30D8              xor al,bl
00000A6D  884500            mov [ebp+0x0],al
00000A70  45                inc ebp
00000A71  EBDC              jmp short 0xa4f
00000A73  01FC              add esp,edi
00000A75  5D                pop ebp
00000A76  5D                pop ebp
00000A77  5F                pop edi
00000A78  5E                pop esi
00000A79  5B                pop ebx
00000A7A  C20800            ret 0x8
00000A7D

```

A7D-9F8=85h=133 bytes but i don't know if calculation is ok because the preciding number of bytes of the same function result 130 bytes... The first argumenti of the function that I name "cript" is the string, the second argumenti is the string lenght (first byte+ key lenght + message lenght). Below there is the assembly language file for obtain that cript routines:

```
; nasmw -fobj  this.asm

section _DATA use32 public class=DATA
global cript
section _TEXT use32 public class=CODE

cript:
      push    ebx
      push    esi
      push    edi
      push    ebp
      push    ebp
      mov     edi,  256
      sub     esp,  edi
      mov     ebp,  dword[esp+  edi+24]
      xor     ebx,  ebx
      mov     bl,  [ebp]
      inc     ebp
      xor     eax,  eax
.1:   mov     [esp+eax],  al
      inc     eax
      cmp     eax,  edi
      jb      .1
      xor     esi,  esi
      xor     ecx,  ecx
.2:   mov     eax,  esi
      xor     edx,  edx
      div     ebx
      mov     al,  [esp+esi]
      add     al,  [ebp+edx]
      add     cl,  al
      mov     al,  [esp+esi]
      mov     dl,  [esp+ecx]
      mov     [esp+ecx],  al
      mov     [esp+esi],  dl
      inc     esi
      cmp     esi,  edi
      jb      .2
      mov     eax,  dword[esp+  edi+28]
      add     eax,  ebp
      jc      .z
      dec     eax
      mov     esi,  eax
      add     ebp,  ebx
      xor     eax,  eax
      xor     edx,  edx
      xor     ecx,  ecx
.3:   cmp     ebp,  esi
      jae     .z
      inc     dl
      mov     al,  [esp+edx]
      add     cl,  al
      mov     bl,  [esp+ecx]
      mov     [esp+ecx],  al
      mov     [esp+edx],  bl ; swap S[c] S[r]
      add     al,  bl
      mov     bl,  [esp+eax]
      mov     al,  [ebp]
      xor     al,  bl
      mov     [ebp],  al
      inc     ebp
      jmp     short  .3
.z:
      add     esp,  edi
      pop     ebp
      pop     ebp
      pop     edi
      pop     esi
      pop     ebx
      ret     8

```

below the C file for check results:

```
// Nasmw  -fobj  fileasm.asm
// bcc32 -v filec.c fileasm.obj
#include <stdio.h>

void _stdcall cript(char*,unsigned);

char es1[]="\x01\x00\x00\x00\x00\x00\x00";
char es2[]="\x0Dthis is a keythis is some data to encrypt";
char es3[]="\x0dthis is a key\xb5\xdb?i\x1f\x92\x96\226e!\xf3\xae(!\xf3\xea\x43\xd4\x9fS\xbd?d\x82\x84{\xcdN";
char es4[]="Sthis is a rather long key because the value of S is 83 so the key length must matchand this is the data to be encrypted";

void printMSGKeyC(unsigned char* a, unsigned len)
{unsigned i,j,k;
 unsigned char *p,*end;

 printf("keylen = %u\nKey    = [", (unsigned)*a);
 for(i=1, j=*a;i<=j;++i) printf("%c", a[i]);
 printf("]\nMessage= [");
 for(p=a+i,end=a+len-1;p<end;++p)printf("%c", *p);
 printf("]\n");
}

void printMSGKeyHex(unsigned  char* a, unsigned len)
{unsigned i,j,k;
 unsigned char *p,*end;

 printf("keylen = %u\nKey    = [", (unsigned)*a);
 for(i=1, j=*a;i<=j;++i) printf("%02x", a[i]);
 printf("]\nMessage= [");
 for(p=a+i,end=a+len-1;p<end;++p)printf("%02x", *p);
 printf("]\n");
}

main()
{printf("sizeof \"%s\"= %u [so the last byte 0 is in the count]\n", "this", sizeof "this");

 printf("Input:\n");
 printMSGKeyHex(es1, sizeof es1);
 cript(es1,  (sizeof es1)-1);
 printf("Afther I cript:\n");
 printMSGKeyHex(es1, sizeof es1);

 printf("Input:\n");
 printMSGKeyC(es2, sizeof es2);
 printMSGKeyHex(es2, sizeof es2);
 cript(es2,  (sizeof es2)-1);
 printf("Afther I cript:\n");
 printMSGKeyC(es2, sizeof es2);
 printMSGKeyHex(es2, sizeof es2);
 cript(es2,  (sizeof es2)-1);
 printf("Afther II cript:\n");
 printMSGKeyC(es2, sizeof es2);
 printMSGKeyHex(es2, sizeof es2);
 printf("----------------------\n");

 printf("Input:\n");
 printMSGKeyHex(es3, sizeof es3);
 cript(es3,  (sizeof es3)-1);
 printf("Afther I cript:\n");
 printMSGKeyHex(es3, sizeof es3);
 printf("----------------------\n");

 printf("Input:\n");
 printMSGKeyHex(es4, sizeof es4);
 cript(es4,  (sizeof es4)-1);
 printf("Afther I cript:\n");
 printMSGKeyHex(es4, sizeof es4);
 cript(es4,  (sizeof es4)-1);
 printf("Afther II cript:\n");
 printMSGKeyHex(es4, sizeof es4);

 return 0;
}

```

the results:

```
 sizeof "this"= 5 [so the last byte 0 is in the count]
Input:
keylen = 1
Key    = [00]
Message= [0000000000]
Afther I cript:
keylen = 1
Key    = [00]
Message= [de188941a3]
Input:
keylen = 13
Key    = [this is a key]
Message= [this is some data to encrypt]
keylen = 13
Key    = [746869732069732061206b6579]
Message= [7468697320697320736f6d65206461746120746f20656e6372797074]
Afther I cript:
keylen = 13
Key    = [this is a key]
Message= [Á█?iÆûûe!¾«(!¾ÛCÈƒS¢?déä{═N]
keylen = 13
Key    = [746869732069732061206b6579]
Message= [b5db3f691f9296966521f3ae2821f3ea43d49f53bd3f6482847bcd4e]
Afther II cript:
keylen = 13
Key    = [this is a key]
Message= [this is some data to encrypt]
keylen = 13
Key    = [746869732069732061206b6579]
Message= [7468697320697320736f6d65206461746120746f20656e6372797074]
----------------------
Input:
keylen = 13
Key    = [746869732069732061206b6579]
Message= [b5db3f691f9296966521f3ae2821f3ea43d49f53bd3f6482847bcd4e]
Afther I cript:
keylen = 13
Key    = [746869732069732061206b6579]
Message= [7468697320697320736f6d65206461746120746f20656e6372797074]
----------------------
Input:
keylen = 83
Key    = [74686973206973206120726174686572206c6f6e67206b65792062656361757365207468652076616c7565206f66205320697320383320736f20746865206b6579206c656e677468206d757374206d61746368]
Message= [616e64207468697320697320746865206461746120746f20626520656e63727970746564]
Afther I cript:
keylen = 83
Key    = [74686973206973206120726174686572206c6f6e67206b65792062656361757365207468652076616c7565206f66205320697320383320736f20746865206b6579206c656e677468206d757374206d61746368]
Message= [961f2c8fa3259ba3665b6d6bdfbcac8b8efafe96423d21fc3b13606316710411d886ee07]
Afther II cript:
keylen = 83
Key    = [74686973206973206120726174686572206c6f6e67206b65792062656361757365207468652076616c7565206f66205320697320383320736f20746865206b6579206c656e677468206d757374206d61746368]
Message= [616e64207468697320697320746865206461746120746f20626520656e63727970746564]

```

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

I considered using only chained functions, but opted to golfify the algorithm given here: https://gist.github.com/farhadi/2185197.

```
A=>eval(`for(C=A[c='charCodeAt']
(),K=A.slice(1,++C),T=A.slice(C),i=j=k=l=m=y=0,s=[],r=[],a=256;i<a;)s[i]=i++
for(;j<a;){t=s[k=(k+s[j]+K[c](j%K.length))%a]
s[k]=s[j]
s[j++]=t}for(;y<T.length;){r[y]=T[c](y++)^s[((t=s[m=(m+s[l=++l%a])%a])+
(s[m]=s[l]))%a]
s[l]=t}r`)

```

## Less Golfed

```
A=>{
  C=A.charCodeAt()
  K=A.slice(1,++C)
  T=A.slice(C)
  for(i=j=k=l=m=y=0,s=[],r=[];i<256;)s[i]=i++
  for(;j<256;){
    t=s[k=(k+s[j]+K.charCodeAt(j%K.length))%256];
    s[k]=s[j];
    s[j++]=t;
  }
  for(;y<T.length;){
    t=s[m=(m+s[l=(l+1)%256])%256];
    s[m]=s[l];
    s[l]=t;
    r[y]=T.charCodeAt(y++)^s[(s[l]+s[m])%256];
  }
  return r;
}

```

```
let f =

A=>eval(`for(C=A[c='charCodeAt']
(),K=A.slice(1,++C),T=A.slice(C),i=j=k=l=m=y=0,s=[],r=[],a=256;i<a;)s[i]=i++
for(;j<a;){t=s[k=(k+s[j]+K[c](j%K.length))%a]
s[k]=s[j]
s[j++]=t}for(;y<T.length;){r[y]=T[c](y++)^s[((t=s[m=(m+s[l=++l%a])%a])+
(s[m]=s[l]))%a]
s[l]=t}r`)
let test = (input, expected) => {
  let output = f(input);
  let chars = output.map(c=>String.fromCharCode(c)).join``;
  let hex = output.map(c=>('0' + c.toString(16)).slice(-2)).join``;
  let success = chars === expected;
  console.log([success ? 'SUCCESS:' : 'ERROR:', output, chars, hex].join`\n`);
}

test('\x01\x00\x00\x00\x00\x00\x00','\xde\x18\x89A\xa3')
test('\x0Dthis is a keythis is some data to encrypt','\xb5\xdb?i\x1f\x92\x96\x96e!\xf3\xae(!\xf3\xeaC\xd4\x9fS\xbd?d\x82\x84{\xcdN')
test('\x0dthis is a key\xb5\xdb?i\x1f\x92\x96\x96e!\xf3\xae(!\xf3\xeaC\xd4\x9fS\xbd?d\x82\x84{\xcdN','this is some data to encrypt')
test('Sthis is a rather long key because the value of S is 83 so the key length must matchand this is the data to be encrypted',
     '\x96\x1f,\x8f\xa3%\x9b\xa3f[mk\xdf\xbc\xac\x8b\x8e\xfa\xfe\x96B=!\xfc;\x13`c\x16q\x04\x11\xd8\x86\xee\x07')
```

# Answer
> 2 votes
# Python 2, 203 bytes

```
def f(x):
	def h():S[i],S[j]=S[j],S[i]
	m=256;x=map(ord,x);S=range(m);l=x.pop(0);j=0
	for i in S[:]:j=(j+S[i]+x[i%l])%m;h()
	i=j=0
	for b in x[l:]:i=(i+1)%m;j=(j+S[i])%m;h();yield chr(S[(S[i]+S[j])%m]^b)

```

Try it online!

`f` is a generator (iterable) of strings.

Ungolfed:

```
def f(x):
    def h():
        S[i], S[j] = S[j], S[i]  # we have to do this two times
    m = 256  # used often
    x = map(ord, x)  # get numbers to do stuff with
    S = range(m)  # init State
    l = x.pop(0)  # get key length and remove the first byte in one go
    j = 0
    for i in S[:]:  # shorter than range(256)
        j = (j + S[i] + x[i%l]) % m
        h()
    i = j = 0
    for b in x[l:]:  # data comes after the key
        i = (i+1) % m
        j = (j+S[i]) % m
        h()
        yield chr(S[(S[i]+S[j]) % m] ^ b)  # convert to str again

```

# Answer
> 2 votes
# , 189 bytes

```
\(s){f=256
S=1:f-1
for(i in 1:f)S[c(i,T)]=S[c(T<-(T-1+S[i]+s[(i-1)%%s[1]+2])%%f+1,i)]
i=j=1
sapply(s[0:-s-1],\(B)bitwXor(S[sum(S[c(j,i)]<<-S[c(i<<-(i)%%f+1,j<<-(j-1+S[i])%%f+1)])%%f+1],B))}

```

Attempt This Online!

Ungolfed code:

```
rc4=function(s){
    l=s[1]
    k=s[1:l+1]
    d=s[-(0:l+1)]
    # initialization
    S=0:255
    # key processing
    j=0
    for(i in 0:255){
        j=(j+S[i+1]+k[i%%l+1])%%256
        temp=S[i+1]
        S[i+1]=S[j+1]
        S[j+1]=temp
        }
    #encryption
    i=j=0
    ans={}
    for(B in d){
        i=(i+1)%%256
        j=(j+S[i+1])%%256
        temp=S[i+1]
        S[i+1]=S[j+1]
        S[j+1]=temp
        K=S[(S[i+1]+S[j+1])%%256+1]
        ans=c(ans,bitwXor(K,B))
    }
    ans
}

```

# Answer
> 1 votes
# Ruby, 234 bytes

Untested.

```
->s{l=s[0].ord;k=s[1..l];i=s[l+1..-1];o='';s=[*0..255];i,j,q=0;256.times{|i|j=(j+s[i]+k[i%k.size].ord)%256;s[i],s[j]=s[j],s[i]};i.size.times{|k|i=(i+1)%256;q=(q+s[i])%256;s[i],s[q]=s[q],s[i];b=s[(s[i]+s[q])%256];o<<(b^i[k].ord).chr;o}

```

# Answer
> 1 votes
# C, 181 bytes

```
f(a,n)char*a;{unsigned char A=*a++,i=-1,j=0,k,s[256];for(;s[i]=i;--i);for(;k=s[i],s[i]=s[j+=k+a[i%A]],s[j]=k,k=++i;);for(n-=A,a+=A;--n;*a++^=s[j+=A])j=s[++i],A=s[i]=s[k+=j],s[k]=j;}

```

thanks to ceilingcat for some bytes less:

```
f(a,n)char*a;
{unsigned char A=*a++,i=-1,j=0,k,s[256];
 for(;s[i]=i;--i);
 for(;k=s[i],s[i]=s[j+=k+a[i%A]],s[j]=k,k=++i;);
 for(n-=A,a+=A;--n;*a++^=s[j+=A])j=s[++i],A=s[i]=s[k+=j],s[k]=j;
}

```

f(a,n) in "a" there would be the array of chars 1Byte len + key + message; in n there is the size of the all array of "a" not count the last '\0'. code for test and result would be as the one used for assembly function.

# Answer
> 1 votes
# APL(NARS), 329 chars, 658 bytes

```
xor←{⍺<0:¯1⋄⍵<0:¯1⋄⍺=0:⍵⋄⍵=0:⍺⋄k←⌈/{⌊1+2⍟⍵}¨⍺⍵⋄(2⍴⍨≢m)⊥m←↑≠/{(k⍴2)⊤⍵}¨⍺⍵}
∇r←C w;s;i;j;l;t;b;x
k←256⋄s←¯1+⍳k⋄i←j←0⋄l←¯1+⎕AV⍳↑w
t←s[1+i]⋄j←k∣¯1+j+t+⎕AV⍳w[2+l∣i]⋄s[1+i]←s[1+j]⋄s[1+j]←t⋄i+←1⋄→2×⍳i<k
i←j←0⋄b←≢w⋄l+←1
l+←1⋄→6×⍳l>b⋄i←k∣i+1⋄t←s[1+i]⋄j←k∣j+t⋄s[1+i]←s[1+j]⋄s[1+j]←t
x←s[1+k∣t+s[1+i]] xor ¯1+⎕AV⍳w[l]⋄w[l]←⎕AV[1+x]⋄→4
r←w
∇

```

as always the error check would be demanded to someone other... This seems to be ok on input and output, test:

```
  str2Hex←{∊{'0123456789ABCDEF'[1+{(2⍴16)⊤⍵}⍵]}¨{¯1+⎕AV⍳⍵}⍵}
  str2Hex ⎕AV[2,1,1,1,1,1,1]
01000000000000
  str2Hex C ⎕AV[2,1,1,1,1,1,1]
0100DE188941A3
  str2Hex C C ⎕AV[2,1,1,1,1,1,1]
01000000000000
  str2Hex C ⎕AV[14],'this is a keythis is some data to encrypt'
0D746869732069732061206B6579B5DB3F691F9296966521F3AE2821F3EA43D49F53BD3F6482847BCD4E
  C C ⎕AV[14],'this is a keythis is some data to encrypt'

this is a keythis is some data to encrypt

  str2Hex C 'Sthis is a rather long key because the value of S is 83 so the key length must matchand this is the data to be encrypted'
5374686973206973206120726174686572206C6F6E67206B65792062656361757365207468652076616C7565206F662053
  20697320383320736F20746865206B6579206C656E677468206D757374206D61746368961F2C8FA3259BA3665B6D
  6BDFBCAC8B8EFAFE96423D21FC3B13606316710411D886EE07

  C C 'Sthis is a rather long key because the value of S is 83 so the key length must matchand this is the data to be encrypted'
Sthis is a rather long key because the value of S is 83 so the key length must matchand this is th
  e data to be encrypted

```

Yes all can be reduced...but for example make more little the xor function could mean make it less general...

# Answer
> 0 votes
# Rust 348

```
fn rc4(n:Vec<u8>)->Vec<u8>{let(mut s,mut j,mut t,l)=((0..256).collect::<Vec<usize>>(),0,0,n[0] as usize);let(key,msg)=n[1..].split_at(l);(0..256).fold(0,|a,i|{j=(a+s[i]+key[i%l] as usize)%256;t=s[i];s[i]=s[j];s[j]=t;j});j=0;(1..).zip(msg.iter()).map(|(i,b)|{j=(j+s[i])%256;t=s[i];s[i]=s[j];s[j]=t;s[(s[i]+s[j])%256]as u8^b}).collect::<Vec<u8>>()}

```

This is quite terribly large, I am hoping maybe someone could provide some suggestions.

ungolfed: on play.rust-lang.org playground

---
Tags: code-golf, encryption
---


# Question
Title: User Appreciation Challenge #1: Dennis ♦
I got the spontaneous idea of making a series of challenges of users that have helped and continue to help the PPCG community be an enjoyable place for everyone, or maybe just specifically for me. :P

If you convert Dennis's name to an array of `1`s and `0`s where each consonant is `1` and each vowel is `0`, the array is `[1, 0, 1, 1, 0, 1]`, which is symmetrical. Thus, your challenge is to determine what other names are like this.

# Challenge

Given an ASCII string, remove all characters that aren't letters and determine if the configuration of vowels and consonants are symmetrical. `y` is not a vowel.

Please note that your program does not have to be this type of string itself.

# Test Cases

```
Dennis -> truthy
Martin -> truthy
Martin Ender -> truthy
Alex -> falsy
Alex A. -> truthy
Doorknob -> falsy
Mego -> falsy

```

# Reference Implementation

This Python 3 code will give the correct output given a test case. It is as ungolfed as I could make it without being ridiculous.

# Python 3

```
s = input()
l = []
for c in s:
	if c in 'AEIOUaeiou':
		l.append(0)
	elif c in 'BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz':
		l.append(1)
print(l == list(reversed(l)), end = '')

```

Try it online!

# Answer
# Vyxal, 4 bytes

```
ǍAḂ⁼

```

Try it Online!

```
Ǎ    # Non-alphabet chars removed
 A   # Vowel mask (1 for vowel, 0 for not)
  Ḃ⁼ # Is equal to its reverse?

```

# Vyxal 2.4.1, 7 bytes

```
Ǎk∨vcḂ⁼

```

Try it Online!

-6 thanks to lyxal
-1 thanks to Underslash
> 2 votes

# Answer
# Jelly, 11 bytes

```
ŒufØAe€ØCŒḂ

```

Try it online!

Alternate versions:

```
ŒlfØae€ØCŒḂ

```

```
ŒufØAe€ØcŒḂ

```

```
ŒlfØae€ØcŒḂ

```

Of course a challenge appreciating Dennis must have an answer in a language of his.
> 20 votes

# Answer
# 05AB1E, 9 bytes

```
žM¹álSåÂQ

```

Try it online!

-2 thanks to Adnan.

This attacks Jelly's pain point exactly. It uses `l` and `A`, 1-byte equivalents for Jelly's `Œl` and `Øa` respectively.
> 18 votes

# Answer
## x86 32-bit machine-code function, ~~42~~ 41 bytes

Currently the shortest non-golfing-language answer, 1B shorter than @streetster's q/kdb+.

**With 0 for truthy and non-zero for falsy: ~~41~~ 40 bytes.** (in general, saves 1 byte for 32-bit, 2 bytes for 64-bit).

**With implicit-length strings (C-style 0-terminated): ~~45~~ 44 bytes**

**x86-64 machine-code (with 32-bit pointers, like the x32 ABI): ~~44~~ 43 bytes**.

**x86-64 with implicit-length strings, still 46 bytes (the shift/mask bitmap strategy is break-even now).**

This is a function with C signature `_Bool dennis_like(size_t ecx, const char *esi)`. The calling convention is slightly non-standard, close to MS vectorcall/fastcall but with different arg registers: string in ESI and the length in ECX. It only clobbers its arg-regs and EDX. AL holds the return value, with the higher bytes of EAX holding garbage (as allowed by the SysV i386 and x32 ABIs, and the Windows x64 calling convention.)

---

**Explanation of the algorithm**:

Loop over the input string, filtering and classifying into a boolean array on the stack: For each byte, check if it's an alphabetic character (if not, continue to next char), and transform it to an integer from 0-25 (A-Z). Use that 0-25 integer to check a bitmap of vowel=0/consonant=1. (The bitmap is loaded into a register as a 32-bit immediate constant). Push 0 or 0xFF onto the stack according to the bitmap result (actually in the low byte of a 32-bit element, which may have garbage in the top 3 bytes).

The first loop produces an array of 0 or 0xFF (in dword elements padded with garbage). Do the usual palindrome check with a second loop that stops when pointers cross in the middle (or when they both point to the same element if there were an odd number of alphabetic characters). The upward-moving pointer is the stack pointer, and we use POP to load+increment. Instead of compare / setcc in this loop, we can just use XOR to detect same/different since there are only two possible values. We could accumulate (with OR) whether we found any non-matching elements, but an early-out branch on flags set by XOR is at least as good.

Notice that the second loop uses `byte` operand-size, so it doesn't care what garbage the first loop leaves outside the low byte of each array element.

---

It uses the undocumented `salc` instruction to set AL from CF, in the same way that `sbb al,al` would. It's supported on every Intel CPU (except in 64-bit mode), even Knight's Landing! Agner Fog lists timings for it on all AMD CPUs as well (including Ryzen), so if x86 vendors insist on tying up that byte of opcode space ever since 8086, we might as well take advantage of it.

Interesting tricks:

* unsigned-compare trick for a combined isalpha() and toupper(), and zero-extends the byte to fill eax, setting up for:
* immediate bitmap in a register for `bt`, inspired by some nice compiler output for `switch`.
* Creating a variable-sized array on the stack with push in a loop. (Standard for asm, but not something you can do with C for the implicit-length string version). It uses 4 bytes of stack space for every input character, but saves at least 1 byte vs. optimal golfing around `stosb`.
* Instead of cmp/setne on the boolean array, XOR booleans together to get a truth value directly. (`cmp`/`salc` isn't an option, because `salc` only works for CF, and 0xFF-0 doesn't set CF. `sete` is 3 bytes, but would avoid the `inc` outside the loop, for a net cost of 2 bytes (1 in 64-bit mode)) vs. xor in the loop and fixing it with inc.

```
; explicit-length version: input string in ESI, byte count in ECX
08048060 <dennis_like>:
 8048060:       55                      push   ebp
 8048061:       89 e5                   mov    ebp,esp  ; a stack frame lets us restore esp with LEAVE (1B)
 8048063:       ba ee be ef 03          mov    edx,0x3efbeee ; consonant bitmap

08048068 <dennis_like.filter_loop>:
 8048068:       ac                      lods   al,BYTE PTR ds:[esi]
 8048069:       24 5f                   and    al,0x5f    ; uppercase
 804806b:       2c 41                   sub    al,0x41    ; range-shift to 0..25
 804806d:       3c 19                   cmp    al,0x19    ; reject non-letters
 804806f:       77 05                   ja     8048076 <dennis_like.non_alpha>
 8048071:       0f a3 c2                bt     edx,eax    # AL = 0..25 = position in alphabet
 8048074:       d6                      SALC     ; set AL=0 or 0xFF from carry.  Undocumented insn, but widely supported
 8048075:       50                      push   eax
08048076 <dennis_like.non_alpha>:
 8048076:       e2 f0                   loop   8048068 <dennis_like.filter_loop>   # ecx = remaining string bytes
 ; end of first loop

 8048078:       89 ee                   mov    esi,ebp  ; ebp = one-past-the-top of the bool array
0804807a <dennis_like.palindrome_loop>:
 804807a:       58                      pop    eax      ; read from the bottom
 804807b:       83 ee 04                sub    esi,0x4
 804807e:       32 06                   xor    al,BYTE PTR [esi]
 8048080:       75 04                   jne    8048086 <dennis_like.non_palindrome>
 8048082:       39 e6                   cmp    esi,esp             ; until the pointers meet or cross in the middle
 8048084:       77 f4                   ja     804807a  <dennis_like.palindrome_loop>

08048086 <dennis_like.non_palindrome>:
 ; jump or fall-through to here with al holding an inverted boolean
 8048086:       40                      inc    eax
 8048087:       c9                      leave
 8048088:       c3                      ret
;; 0x89 - 0x60 = 41 bytes

```

This is probably also one of the fastest answers, since none of the golfing really hurts too badly, at least for strings under a few thousand characters where the 4x memory usage doesn't cause a lot of cache-misses. (It might also lose to answers that take an early-out for non-Dennis-like strings before looping over all the characters.) `salc` is slower than `setcc` on many CPUs (e.g. 3 uops vs. 1 on Skylake), but a bitmap check with `bt/salc` is still faster than a string-search or regex-match. And there's no startup overhead, so it's extremely cheap for short strings.

Doing it in one pass on the fly would mean repeating the classification code for the up and down directions. That would be faster but larger code-size. (Of course if you want fast, you can do 16 or 32 chars at a time with SSE2 or AVX2, still using the compare trick by range-shifting to the bottom of the signed range).

---

**Test program (for ia32 or x32 Linux)** to call this function with a cmdline arg, and exit with status = return value. `strlen` implementation from int80h.org.

```
; build with the same %define macros as the source below (so this uses 32-bit regs in 32-bit mode)
global _start
_start:
    ;%define PTRSIZE 4   ; true for x32 and 32-bit mode.

    mov  esi, [rsp+4 + 4*1]  ; esi = argv[1]
    ;mov  rsi, [rsp+8 + 8*1]  ; rsi = argv[1]   ; For regular x86-64 (not x32)

%if IMPLICIT_LENGTH == 0
        ; strlen(esi)
         mov     rdi, rsi
         mov     rcx, -1
        xor     eax, eax
        repne scasb    ; rcx = -strlen - 2
        not     rcx
        dec     rcx
%endif

    mov  eax, 0xFFFFAEBB   ; make sure the function works with garbage in EAX
    call dennis_like

    ;; use the 32-bit ABI _exit syscall, even in x32 code for simplicity
    mov ebx, eax
    mov eax, 1
    int 0x80           ; _exit( dennis_like(argv[1]) )

    ;; movzx edi, al   ; actually mov edi,eax is fine here, too
    ;; mov eax,231     ; 64-bit ABI exit_group( same thing )
    ;; syscall

```

---

A 64-bit version of this function could use `sbb eax,eax`, which is only 2 bytes instead of 3 for `setc al`. It would also need an extra byte for `dec` or `not` at the end (because only 32-bit has 1-byte inc/dec r32). Using the x32 ABI (32-bit pointers in long mode), we can still avoid REX prefixes even though we copy and compare pointers.

`setc [rdi]` can write directly to memory, but reserving ECX bytes of stack space costs more code-size than that saves. (And we need to move through the output array. `[rdi+rcx]` takes one extra byte for the addressing mode, but really we need a counter that doesn't update for filtered characters so it's going to be worse than that.)

---

**This is the YASM/NASM source with `%if` conditionals. It can be built with `-felf32` (32-bit code) or `-felfx32` (64-bit code with the x32 ABI), and with implicit or explicit length**. I've tested all 4 versions. See this answer for a script to build a static binary from NASM/YASM source.

To test the 64-bit version on a machine without support for the x32 ABI, you can change the pointer regs to 64-bit. (Then simply subtract the number of REX.W=1 prefixes (0x48 bytes) from the count. In this case, 4 instructions need REX prefixes to operate on 64-bit regs). Or simply call it with the `rsp` and the input pointer in the low 4G of address space.

```
%define IMPLICIT_LENGTH 0

; This source can be built as x32, or as plain old 32-bit mode
; x32 needs to push 64-bit regs, and using them in addressing modes avoids address-size prefixes
; 32-bit code needs to use the 32-bit names everywhere

;%if __BITS__ != 32   ; NASM-only
%ifidn __OUTPUT_FORMAT__, elfx32
%define CPUMODE 64
%define STACKWIDTH 8    ; push / pop 8 bytes
%else
%define CPUMODE 32
%define STACKWIDTH 4    ; push / pop 4 bytes
%define rax eax
%define rcx ecx
%define rsi esi
%define rdi edi
%define rbp ebp
%define rsp esp
%endif

    ; A regular x86-64 version needs 4 REX prefixes to handle 64-bit pointers
    ; I haven't cluttered the source with that, but I guess stuff like %define ebp rbp  would do the trick.

    ;; Calling convention similar to SysV x32, or to MS vectorcall, but with different arg regs
    ;; _Bool dennis_like_implicit(const char *esi)
    ;; _Bool dennis_like_explicit(size_t ecx, const char *esi)
global dennis_like
dennis_like:
    ; We want to restore esp later, so make a stack frame for LEAVE
    push  rbp
    mov   ebp, esp   ; enter 0,0 is 4 bytes.  Only saves bytes if we had a fixed-size allocation to do.

    ;         ZYXWVUTSRQPONMLKJIHGFEDCBA
    mov  edx, 11111011111011111011101110b   ; consonant/vowel bitmap for use with bt

;;; assume that len >= 1
%if IMPLICIT_LENGTH
    lodsb   ; pipelining the loop is 1B shorter than  jmp .non_alpha
.filter_loop:
%else
.filter_loop:
    lodsb
%endif

    and   al, 0x7F ^ 0x20  ; force ASCII to uppercase.
    sub   al, 'A'          ; range-shift to 'A' = 0
    cmp   al, 'Z'-'A'      ; if al was less than 'A', it will be a large unsigned number
    ja  .non_alpha
    ;; AL = position in alphabet (0-25)

    bt    edx, eax              ; 3B
%if CPUMODE == 32
    salc                        ; 1B   only sets AL = 0 or 0xFF.  Not available in 64-bit mode
%else
    sbb   eax, eax              ; 2B   eax = 0 or -1, according to CF.
%endif
    push  rax

.non_alpha:
%if IMPLICIT_LENGTH
    lodsb
    test   al,al
    jnz .filter_loop
%else
    loop .filter_loop
%endif
    ; al = potentially garbage if the last char was non-alpha
    ; esp = bottom of bool array

    mov   esi, ebp  ; ebp = one-past-the-top of the bool array
.palindrome_loop:
    pop   rax

    sub   esi, STACKWIDTH
    xor   al, [rsi]   ; al = (arr[up] != arr[--down]).  8-bit operand-size so flags are set from the non-garbage
    jnz .non_palindrome

    cmp   esi, esp
    ja .palindrome_loop

.non_palindrome:  ; we jump here with al=1 if we found a difference, or drop out of the loop with al=0 for no diff
    inc   eax     ;; AL transforms 0 -> 1  or  0xFF -> 0.
    leave
    ret           ; return value in AL.  high bytes of EAX are allowed to contain garbage.

```

I looked at messing around with DF (the direction flag that controls `lodsd` / `scasd` and so on), but it just didn't seem to be a win. The usual ABIs require that DF is cleared on function entry and exit. Assuming cleared on entry but leaving it set on exit would be cheating, IMO. It would be nice to use LODSD / SCASD to avoid the 3-byte `sub esi, 4`, especially in the case where there's no high-garbage.

---

### Alternate bitmap strategy (for x86-64 implicit-length strings)

It turns out this doesn't save any bytes, because `bt r32,r32` still works with high garbage in the bit-index. It's just not documented the way `shr` is.

Instead of `bt / sbb` to get the bit into / out of CF, use a shift / mask to isolate the bit we want from the bitmap.

```
%if IMPLICIT_LENGTH && CPUMODE == 64
    ; incompatible with LOOP for explicit-length, both need ECX.  In that case, bt/sbb is best
    xchg  eax, ecx
    mov   eax, 11111011111011111011101110b   ; not hoisted out of the loop
    shr   eax, cl
    and   al, 1
%else
    bt    edx, eax
    sbb   eax, eax
%endif
    push  rax

```

Since this produces 0/1 in AL at the end (instead of 0/0xFF), we can do the necessary inversion of the return value at the end of the function with `xor al, 1` (2B) instead of `dec eax` (also 2B in x86-64) to still produce a proper `bool` / `_Bool` return value.

This used to save 1B for x86-64 with implicit-length strings, by avoiding the need to zero the high bytes of EAX. (I had been using `and eax, 0x7F ^ 0x20` to force to upper-case and zero the rest of eax with a 3-byte `and r32,imm8`. But now I'm using the 2-byte immediate-with-AL encoding that most 8086 instructions have, like I was already doing for the `sub` and `cmp`.)

It loses to `bt`/`salc` in 32-bit mode, and explicit-length strings need ECX for the count so this doesn't work there either.

But then I realized that I was wrong: `bt edx, eax` still works with high garbage in eax. It masks the shift count the same way `shr r32, cl` does (looking only at the low 5 bits of cl). This is different from `bt [mem], reg`, which can access outside the memory referenced by the addressing-mode/size, treating it as a bitstring. (Crazy CISC...)

Intel's insn set ref manual entry for `bt` does document the masking in the description section: *If the bit base operand specifies a register, the instruction takes the modulo 16, 32, or 64 of the bit offset operand (modulo size depends on the mode and register size).* Apparently I missed it when writing this answer originally; I checked a Jan 2015 version of the PDF and it was already there.

A neat trick here is using `xchg eax,ecx` (1 byte) to get the count into CL. Unfortunately, BMI2 `shrx eax, edx, eax` is 5 bytes, vs. only 2 bytes for `shr eax, cl`. Using `bextr` needs a 2-byte `mov ah,1` (for the number of bits to extract), so it's again 5 + 2 bytes like SHRX + AND.

---

The source code has gotten pretty messy after adding `%if` conditionals. **Here's disassembly of x32 implicit-length strings** (using the alternate strategy for the bitmap, so it's still 46 bytes).

The main difference from the explicit-length version is in the first loop. Notice how there's a `lods` before it, and at the bottom, instead of just one at the top of the loop.

```
    ; 64-bit implicit-length version using the alternate bitmap strategy
    00400060 <dennis_like>:
      400060:       55                      push   rbp
      400061:       89 e5                   mov    ebp,esp
      400063:       ac                      lods   al,BYTE PTR ds:[rsi]

    00400064 <dennis_like.filter_loop>:
      400064:       24 5f                   and    al,0x5f
      400066:       2c 41                   sub    al,0x41
      400068:       3c 19                   cmp    al,0x19
      40006a:       77 0b                   ja     400077 <dennis_like.non_alpha>
      40006c:       91                      xchg   ecx,eax
      40006d:       b8 ee be ef 03          mov    eax,0x3efbeee  ; inside the loop since SHR destroys it
      400072:       d3 e8                   shr    eax,cl
      400074:       24 01                   and    al,0x1
      400076:       50                      push   rax
    00400077 <dennis_like.non_alpha>:
      400077:       ac                      lods   al,BYTE PTR ds:[rsi]
      400078:       84 c0                   test   al,al
      40007a:       75 e8                   jne    400064 <dennis_like.filter_loop>

      40007c:       89 ee                   mov    esi,ebp
    0040007e <dennis_like.palindrome_loop>:
      40007e:       58                      pop    rax
      40007f:       83 ee 08                sub    esi,0x8
      400082:       32 06                   xor    al,BYTE PTR [rsi]
      400084:       75 04                   jne    40008a <dennis_like.non_palindrome>
      400086:       39 e6                   cmp    esi,esp
      400088:       77 f4                   ja     40007e <dennis_like.palindrome_loop>

    0040008a <dennis_like.non_palindrome>:
      40008a:       ff c8                   dec    eax  ; invert the 0 / non-zero status of AL.  xor al,1 works too, and produces a proper bool.
      40008c:       c9                      leave
      40008d:       c3                      ret

   0x8e - 0x60 = 0x2e = 46 bytes

```

Update: instead of using 32-bit pointers, I could have used `push rsp` / `pop rbp` to copy a 64-bit register in 2 bytes of code. (Tips for golfing in x86/x64 machine code). But `sub rsi,0x8` and `cmp rsi,rsp` would need REX prefixes which I'm avoiding here by using 32-bit pointers. Perhaps comparing the low 32 could work if the stack doesn't cross a 4GiB boundary, so just the `sub`.

I wonder if `pop rdx` / `std` / `lodsq` / `cld` / `xor al, dl` could work? No, that's 7 bytes, break-even with just using `sub rsi, 8` in the loop body.
> 18 votes

# Answer
# Retina, ~~49 47~~ 45 bytes

```
\P{L}

i`[aeiou]
1
\D
2
+`^(.)(.*)\1$
$2
^.?$

```

Try it online!

Saved 2 bytes thanks to Neil.

Saved another 2 bytes thanks to Martin.

Removes non-letters then replaces vowels with 1 and consonants with 2, to get consistent values. Then repeatedly removes the first and last character if they are the same. Once they aren't, the word was symmetric if there are one or zero characters remaining.
> 8 votes

# Answer
# PHP, 82 Bytes

```
<?=strrev($s=preg_replace(["#[^a-z]#i","#[aeiou]#i","#\pL#"],["",0,1],$argn))==$s;

```

Try it online!
> 7 votes

# Answer
# MATL, 14 bytes

```
t3Y2m)13Y2mtP=

```

Try it at MATL Online.

Here is a slightly modified version to check all test cases.

**Explanation**

```
        % Implicitly grab the input as a string
        %     STACK: {'Martin Ender'}
t       % Duplicate the input
        %     STACK: {'Martin Ender', 'Martin Ender'}
3Y2     % Push the string 'ABC...XYZabc...xyz'
        %     STACK: {'Martin Ender', 'Martin Ender', 'ABC...XYZabc...xyz'}
m       % Find which characters of the input are letters using this string
        %     STACK: {'Martin Ender', [1 1 1 1 1 1 0 1 1 1 1]}
)       % Use this boolean array to select only the letters
        %     STACK: {'MartinEnder'}
13Y2    % Push the string literal 'aeiouAEIOU' to the stack
        %     STACK: {'MartinEnder', 'aeiouAEIOU'}
m       % Check for membership of each letter of the input in this string.
        %     STACK: {[0 1 0 0 1 0 1 0 0 1 0]}
tP      % Create a reversed copy
        %     STACK: {[0 1 0 0 1 0 1 0 0 1 0], [0 1 0 0 1 0 1 0 0 1 0]}
=       % Perform an element-wise comparison yielding a truthy (all 1's) or
        % falsey (any 0's) result
        %     STACK: {[1 1 1 1 1 1 1 1 1 1 1]}
        % Implicitly display the result

```
> 7 votes

# Answer
# Haskell, 84 75 74 69 bytes

-10 thanks to @nimi
-5 thanks to @Zgarb

```
f x=(==)<*>reverse$[elem c"aeiouAEIOU"|c<-x,'@'<c,c<'{','`'<c||c<'[']

```

The list comprehension replaces each letter with a boolean and removes all other characters. The first part checks whether or not the resulting list is a palindrome.

Try it online!
> 6 votes

# Answer
# Pyth, ~~18~~ 15 bytes

```
_I/L"aeiou"@Gr0

```

Try it here.

-2 thanks to KarlKastor, and subsequently -1.
> 5 votes

# Answer
# Brachylog, 13 bytes

```
ḷ{∈Ṿg|∈Ḅg}ˢ.↔

```

Try it online!

### Explanation

```
ḷ                Lowercase the input
 {       }ˢ.     Select each char if:
  ∈Ṿg              it's a vowel, and replace it with ["aeiou"]
     |             Or
      ∈Ḅg          it's a consonant, and replace it with ["bcdfghjklkmnpqrstvwxyz"]
           .↔    The resulting list is a palindrome

```
> 5 votes

# Answer
## JavaScript (ES6), ~~72~~ 69 bytes

*Saved 3 bytes thanks to Neil*

Returns a boolean.

```
s=>(a=s.match(/[a-z]/gi).map(c=>!/[aeiou]/i.exec(c)))+''==a.reverse()

```

### Test cases

```
let f =

s=>(a=s.match(/[a-z]/gi).map(c=>!/[aeiou]/i.exec(c)))+''==a.reverse()

console.log(f("Dennis"))        // -> truthy
console.log(f("Martin"))        // -> truthy
console.log(f("Martin Ender"))  // -> truthy
console.log(f("Alex"))          // -> falsy
console.log(f("Alex A."))       // -> truthy
console.log(f("Doorknob"))      // -> falsy
console.log(f("Mego"))          // -> falsy
```
> 3 votes

# Answer
# Python 3, ~~72~~ 71 bytes

-1 byte thanks to @ovs

```
def f(s):s=[c in'AEIOU'for c in s.upper()if'@'<c<'['];return s==s[::-1]

```

Try it online!
> 3 votes

# Answer
# Alice, 28 bytes

```
/uia.QN."-e@
\1"lyuy.Ra$i1/o

```

Try it online!

Outputs `1` as truthy and nothing as falsy.

### Explanation

Every command in this program executes in ordinal mode, but with a slight twist in the template that allows me to save a byte. If a newline is an acceptable truthy value, I can save one more byte by the same method.

Linearized, the program is as follows:

```
1il.uN."aei ou"ayQy.R-$@1o1@

1                           % Append "1" to top of stack
                            % STACK: ["1"]
 i                          % Push input to stack
                            % STACK: ["1", "Dennis"]
  l                         % Convert to lowercase
                            % STACK: ["1", "dennis"]
   .                        % Duplicate
                            % STACK: ["1", "dennis", "dennis"]
    u                       % Convert to uppercase
                            % STACK: ["1", "dennis", "DENNIS"]
     N                      % Take multiset difference; this removes all non-alphabetic characters
                            % STACK: ["1", "dennis"]
      .                     % Duplicate
                            % STACK: ["1", "dennis", "dennis"]
       "aei ou"             % Push "aei ou"
                            % STACK: ["1", "dennis", "dennis", "aei ou"]
              a             % Push newline
                            % STACK: ["1", "dennis", "dennis", "aeiou", "\n"]
               y            % Transliterate: replace all vowels with newlines
                            % STACK: ["1", "dennis", "d\nnn\ns"]
                Q           % Reverse stack
                            % STACK: ["d\nnn\ns", "dennis", "1"]
                 y          % Transliterate: replace remaining characters with "1"
                            % STACK: ["1\n11\n1"]
                  .         % Duplicate
                            % STACK: ["1\n11\n1", "1\n11\n1"]
                   R        % Reverse top of stack
                            % STACK: ["1\n11\n1", "1\n11\n1"]
                    -       % Remove occurrences: for same-length strings, result is "" iff strings are equal.
                            % STACK: [""]
                     $      % Pop stack, and skip next command if ""
                      @     % Terminate (skipped if c/v pattern is palindromic)
                       1o   % Output "1"
                         1  % Push "1" (useless)
                          @ % Terminate

```
> 3 votes

# Answer
# Braingolf,  ~~4~~  3 bytes

```
&JP

```

*-1 byte thanks to Erik the Outgolfer*

Turns out I had `P` all along, even before this challenge.

~~`J` however, despite being created before this challenge, wasn't pushed to github before the challenge, thus is still non-competing.~~

### Explanation:

```
&JP  Implicit input, push ASCII value of each char in string to stack
&J   Replace each item in stack with 1 if vowel, otherwise 0
  P  Pop entire stack, push 1 if stack is palindromic, 0 otherwise
     Implicit output of last item on stack

```
> 3 votes

# Answer
# Python 3, ~~92~~ ~~87~~ ~~74~~ ~~72~~ ~~69~~ 68 bytes

```
l=[c in'aeouiAEOUI'for c in input()if c.isalpha()]
print(l==l[::-1])

```

Try it online!
> 2 votes

# Answer
# CJam, 26 bytes

```
lel_'{,97>--"aeiou"fe=_W%=

```

Try it online!

-1 thanks to Esolanging Fruit.
> 2 votes

# Answer
# Mathematica, 113 bytes

```
PalindromeQ@StringCases[StringReplace[#,{Characters["aeiouAEIOU"]->"1",CharacterRange["A","z"]->"0"}],{"0","1"}]&

```
> 2 votes

# Answer
# q/kdb+, ~~42~~ 38 bytes

**Solution:**

```
{x~|:[x]}{inter[x;.Q.a]in"aeiou"}lower

```

**Example:**

```
q){x~|:[x]}{inter[x;.Q.a]in"aeiou"}lower"Dennis"
1b
q){x~|:[x]}{inter[x;.Q.a]in"aeiou"}lower"Adam"
0b
q){x~|:[x]}{inter[x;.Q.a]in"aeiou"}lower"Alex A."
1b

```

**Explanation:**

```
lower        // converts argument on the right to lowercase
.Q.a         // lowercase alphabet "abc..xyz"
inter[x;y]   // intersection of x and y (thus only return a-z)
x in "aeiou" // returns boolean list whether x is a vowel; "dennis" = 010010b
|:           // k shorthand for 'reverse'

```

**Edits:**

* -4 bytes; switching out `reverse` for k equivalent `|:`
> 2 votes

# Answer
# GolfScript, 42 bytes

```
{123,65>.26>6<-?)},{"AEIOUaeiou"?)!}%.-1%=

```

Try it online!

The hard part is generating both the uppercase and lowercase alphabet in one string, which we'll use in a filter function to filter the letters out of the input. Luckily, since strings in GolfScript are just codepoint arrays with a special property, so we can just generate the codepoints in an efficient way. Here's how we generate them:

First, we generate range \[0..122\], 122 being the codepoint for `z`. Then, we take the elements from the element at index 65 onwards. 65 is the codepoint for `A`. Right now, we have \[65..122\]. All fine, except we have some unwanted codepoints (\[91..96\]) in there. So, we first make a duplicate of that range. Then, we take the elements from index 26 onwards, and we have \[91..122\]. After that, we get the elements up to and including index 5. Now we have \[91..96\]. Finally, we remove those elements from our \[65..122\], leaving us wil \[65..90, 97..122\]. Those are the codepoints we want.

Now that we made the upper/lower alphabet codepoint list, we continue our filtering function. The function gets mapped to each character on the input string, which, as I initially said, gets parsed as its codepoint instead. So now we essentially have `[codepoint, [65..90, 97..122]]`. To find out if char `codepoint` is a letter, we simply take its index in the list we made. If it isn't there, we'll get `-1` as the index instead.

Right now, we get a falsey value only if `codepoint == 65`, i.e. the first index of our list, since only then would the index be 0. But a single increment will fix this problem, and, now, if `codepoint` is in our list, we'll get its index + 1, which is always a positive number, thus always truthy, while if it's not there we'll get -1 + 1 = 0, i.e. falsey.

We finally apply the function I described to every char of the input, and we only take the chars for which the function returned a truthy result.

Next up we have to determine if each char is a vowel or consonant. Since the vowels are fewer than the consonants, creating a string of vowels so that we check for that condition is shorter than creating a string of consonants, so we check if each char is a vowel. But, to check if the boolean list is palindromic, we need booleans, which we don't get just by taking the index + 1, since that can result in any number of \[1..10\] if the char is a vowel. And, as most golfing languages, this one, doesn't have a `bool` function either. So, we simply use `not not x`, since `not` always returns a boolean. But wait; do we really need to have specific booleans? Since `not` always returns a boolean, why don't we just remove the second `not`, and actually check if each char is a consonant? Yeah, that's exactly what we'll do!

After the check, which returns a list of booleans, we check if this boolean list we got is a palindrome, which is what this challenge asks us to do. Well, what is the definition of a palindrome? Yes, a palindrome is a list or string which is equal to its reverse. So, how do we check? Simple, we duplicate it, take its reverse, and check against the original list. The result we get is, *finally*, what our code should return.
> 2 votes

# Answer
# PHP, 87 bytes

Regex free PHP version. Added a "vowel" since stripos can return 0 which is false in PHP.

Flaw fixed by Jörg.

```
for(;a&$c=$argn[$p++];)!ctype_alpha($c)?:$s.=stripos(_aeiou,$c)?0:1;echo$s==strrev($s);

```

Try it online!
> 2 votes

# Answer
# Stax, 18 bytes

```
⌠╟%╜«¥│▒g♦°pC₧╤WsV

```

Run and debug it

## Explanation

```
^"[^A-Z]"zR{VVI0<FLcr=
^                      capitalize input
 "[^A-Z]"zR            remove all non alphabet characters
           {     F     loop over modified string
            VV         "AEIOU"
              I        Index of character (-1 if not present)
               0<      less than 0
                       push the result to stack
                  L    wrap the stack in an array
                   c   duplicate it
                    r  reverse it
                     = are they equal?

```
> 2 votes

# Answer
# APL (Dyalog Unicode), ~~34~~ ~~33~~ 24 bytes

Saved bytes thanks to Adám

```
≡∘⌽⍨'AEIOU'∊⍨⎕a∩⍨819⌶⍨∘1

```

Try it online!

`819⌶⍨∘1` uppercase argument

`⎕a∩⍨` intersection with uppercase alphabet

`'AEIOU'∊⍨` belongs-to-`'AEIOU'`? resulting in a boolean vector

`≡∘⌽⍨` reversed equivalent to self?
> 1 votes

# Answer
# Python 2, 83 bytes

```
def f(x):k=map(lambda y:y.lower()in"aeiou",filter(str.isalpha,x));return k==k[::-1]

```

Defines a function that either gives `True` or `False`
> 1 votes

# Answer
# CJam, 79 bytes

First-timer! (I did what I could)

```
r{:X"AEIOUaeiou"#W>{X"BCDFGHJKLMNPQRSTVWXYZbdfghjklmnpqrstvwxyz"#W={'0}&}'1?~}%

```

Try it online!
> 1 votes

# Answer
# Japt v2.0a0, ~~19~~ 11 bytes

```
k\L mè\v ê¬

```

Try it online

---

## Explanation

```
        :Implicit input of string U.
 k\L    :Remove all non-letter characters from U.
 m      :Map over resulting string, replacing each character ...
 è\v    :with the count of the number of vowels in each single character substring.
 ê¬     :Is the above a palindrome?
        :Implicit output of boolean result.

```
> 1 votes

# Answer
# Ruby, 57 bytes

```
->s{x=s.scan(/\p{L}/).map{|c|c=~/[aeiou]/i};x==x.reverse}

```

Try it online!
> 1 votes

# Answer
# Bash, 82 bytes

```
i=${1//[^a-zA-Z]};a=aeouiAEOUI;b=${i//[$a]/0};c=${b//[!0$a]/1};[ $c = `rev<<<$c` ]

```

Try it online!

Recives name as parameter, removes non-leters, replaces vowels with 0, non-vowels nor 0 with 1 and compares with same reversed.

Could golf some more if can get to work double or triple substitution

Exit status is 0 for true and 1 for no.
> 1 votes

# Answer
## Perl, 42 bytes

```
s!(.)\PL*!1+aeiou=~lc$1!ge;$_=$_==reverse

```

Run with `perl -p`.
> 1 votes

# Answer
# 64-bit machine code, 89 bytes.

A function of following signature: `eax = f(char * edi)`

```
48 89 F8 48 89 FE 41 B8 22 82 20 00 8A 0E 84 C9
74 23 89 CA 83 E2 DF 0F BE D2 83 EA 41 83 FA 19
77 0E 44 89 C2 48 FF C0 D3 FA 83 E2 01 88 50 FF
48 FF C6 EB D7 C6 00 02 48 FF C7 48 FF C8 8A 17
40 8A 30 40 38 77 FF 75 05 80 FA 02 75 EA 31 C0
80 FA 02 0F 94 C0 C3

```

Assembled using NASM, from such assembly code:

```

; edi => input string.
; eax <= 1 or 0.

; notes:
; the string needs to be null terminated and located in a
; writable memory location, as it will be mutated.

BITS 64

DENNIS: MOV RAX, RDI
        MOV RSI, RDI
        MOV R8D, 0x208222
.CTOR:  MOV CL, BYTE [RSI]
        TEST CL, CL
        JE .SP
        MOV EDX, ECX
        AND EDX, -33
        MOVSX EDX, DL
        SUB EDX, 65
        CMP EDX, 25
        JA .LI
        MOV EDX, R8D
        INC RAX
        SAR EDX, CL
        AND EDX, 1
        MOV BYTE [RAX-1], DL
.LI:    INC RSI
        JMP .CTOR
.SP:    MOV BYTE [RAX], 2
.EQL:   INC RDI
        DEC RAX
        MOV DL, BYTE [RDI]
        MOV SIL, BYTE [RAX]
        CMP BYTE [RDI-1], SIL
        JNE .EQE
        CMP DL, 2
        JNE .EQL
.EQE:   XOR EAX, EAX
        CMP DL, 2
        SETE AL
        RET

```

Not a killer, not even close, but it has a couple of advantages over the 41-byte answer:

* Requires no memory (not even stack).
* Doesn't require to check the length of a string - it uses null-termination instead.
* Doesn't use undocumented CPU instructions.

Just my $0.02 :).
> 1 votes

# Answer
# Ly, ~~84~~ 64 bytes

```
"aeiou">0i['aL[p' +0]ps'a,Gf'z`Lfp*[p<l~sp>rlr0]p]p&sJ>lrJs<l=u;

```

Try it online!

Still not that short, but getting a stack oriented language with no concept of characters to do this seemed interesting enough to submit. Plus it's a lot shorter than the initial version I posted in June...

1. Setup a vowel testing stack

```
    "aeiou"   - push vowels onto a stack
           >  - swtich to a clean stack

```
2. Switch to an input processing stack, prep input

```
    0   - add a "0", acts as a stopper
     i  - read input into the stack as codepoints

```
3. Check each codepoint/char on the stack, building a `0|1` list

```
    [                                      ]p - loop over the stack
     'aL[p' +0]p                              - lowercase the char
                s                             - stash the character
                 'a,Gf'z`Lfp*                 - check if in "a-z" (3.1)
                             [p<l~sp>rlr0]p   - do 0,1 vowel check (3.2)

```

3.1 Make sure the character is in `a-z`

```
'a,G          - load "a", decrement, do ">" check
    f         - pull char forward (flip top two on stack)
     'z`L     - load "z", increment, do "<" check
         fp   - pull char forward, delete it
           *  - compute "and" of two tests

```

3.2 Compare char to vowel list, generate `0` or `1` result

```
    [p         0]p  - if/then, true if char in "a-z"
      <             - switch to "vowel check" stack
       l            - load current char
        ~           - search stack, get 0,1 result
         sp         - save results, delete from stack
           >        - switch to processing stack
            rlr     - reverse stack, load result, reverse again

```
4. Compare `0|1` list against it's reverse

```
    &s             - copy the 0,1 stack to the backup cell
      J            - join the stack elements
       >lrJs       - repeat on another stack, reversed
            <l     - switch back, load 2nd joined stack
              =u;  - print 0,1 depending on equals check

```
> 1 votes

# Answer
# C (gcc), 130 bytes

```
d(a,l)char*a,*l;{char*y=alloca(*l),*z=y;for(*l=1;*a;a++)if(isalpha(*a))*y++=!strchr("aeiou",*a|32);for(a=y-z;a--;*l*=*z++==*--y);}

```

Try it online!

Takes input as the string and its length, with the length passed by reference (`d(str, &len)`), and outputs by modifying `len`.
> 1 votes

# Answer
# Arturo, 58 bytes

```
$=>[=reverse<=map replace&{/\p{^L}}""=>[in?&"aeiouAEIOU"]]

```

Try it
> 1 votes

# Answer
# Scala 3, 78 bytes

Golfed version. Attempt it online!

```
_.filter(_.isLetter).map(c=>"aeiou".contains(c.toLower)).pipe(c=>c==c.reverse)

```

Ungolfed version. Try it online!

```
case class Test(input: String, output: Boolean)

object Main {
  def f(s:String): Boolean = {
    val filtered = s.filter(_.isLetter)
    val vowels = "aeiou"
    val isVowel = filtered.map(c => vowels.contains(c.toLower))
    isVowel == isVowel.reverse
  }
  def main(args: Array[String]): Unit = {
    val tests = List(
      Test("Dennis", true),
      Test("Martin", true),
      Test("Martin Ender", true),
      Test("Alex", false),
      Test("Alex A.", true),
      Test("Doorknob", false),
      Test("Mego", false)
    )
    for (Test(input, expected) <- tests) {
      val actual = f(input)
      if (actual != expected) throw new AssertionError()
    }
  }
}

```
> 1 votes

# Answer
# Thunno 2, 4 bytes

```
ỊṃḲ⁼

```

#### Explanation

```
ỊṃḲ⁼  # Implicit input
Ị     # Remove non-alphabets
 ṃ    # For each character: 1 if vowel, 0 otherwise
  Ḳ   # Bifurcate (i.e. duplicate and reverse)
   ⁼  # Are the two lists exactly equal?
      # Implicit output

```

#### Screenshot

(click to enlarge)
> 1 votes

# Answer
# Python 3, 65 bytes

```
lambda s:(l:=[c in'aeiou'for c in s.lower()if'`'<c<'{'])==l[::-1]

```

Try it online!
> 1 votes

# Answer
## PowerShell, 108 bytes

```
read-host|%{[char[]]$_|%{$d=$_-replace'\P{L}'-replace'[aeiou]',0-replace'\D',1;$s="$s$d";$r="$d$r"};$s-eq$r}

```
> 0 votes

# Answer
# Axiom, 126 bytes

```
g(x)==~member?(x,alphabetic());v(s:String):Boolean==(w:=remove(g,s);a:=[member?(w.r,"aeiouAEIOU")for r in 1..#w];a=reverse(a))

```

test

```
(8) -> [[i,v(i)] for i in ["Dennis", "Martin", "Martin Ender", "Alex", "Alex A.", "Doorknob", "Mego"]]
   (8)
   [["Dennis",true], ["Martin",true], ["Martin Ender",true], ["Alex",false],
    ["Alex A.",true], ["Doorknob",false], ["Mego",false]]
                                                      Type: List List Any

```
> 0 votes

# Answer
# Actually, 20 bytes

```
ù⌠úc⌡░⌠"aeiou"c⌡M;R=

```

Try it online! (runs all test cases)

-3 bytes from Erik the Outgolfer's suggestion on a different answer

Explanation:

```
ù⌠úc⌡░⌠"aeiou"c⌡M;R=
ù                     lowercase input
 ⌠úc⌡░                characters where function is truthy:
  úc                    is the character a lowercase letter?
      ⌠"aeiou"c⌡M     for each letter:
       "aeiou"c         does the vowel string contain the letter?
                 ;R=  compare equality with reverse (is it a palindrome?)

```
> 0 votes

# Answer
# Retina, 47 bytes

```
i(`[^a-z]

[aeiou]
1
\D
0
+`^(.)(.*)\1$
$2
^.?$

```

Try it online!

This is just a different approach for non alphabet chars
> 0 votes

# Answer
## Pyke, 12 bytes

```
#B)l1~-L{D_q

```

Try it here!

```
#B)          -    filter(is_alpha, input)
   l1        -   ^.lower()
     ~-L{    -  ^ - "bcdfghjklmnpqrstvwxyz"
         D_q - ^ == reversed(^)

```
> 0 votes

# Answer
# PowerShell, 87 Bytes

```
$s=("$args"-replace '\P{L}'-replace'[aeiou]',0-replace'\D',1);$s-eq(-join($s[-1..-99]))

```

Get a copy of the string where vowels are 0 and consonants are 1, with all special chars removed, compare that string to a reversed version joined back to a string

Output:

```
PS C:\Users\Connor> "Dennis","Martin","Martin Ender","Alex","Alex A.","Doorknob","Mego" | % {
    $s=("$_"-replace '\P{L}'-replace'[aeiou]',0-replace'\D',1);$s-eq(-join($s[-1..-99]))
}
True
True
True
False
True
False
False

```
> 0 votes

# Answer
# Google Sheets, 248 bytes

```
=ArrayFormula(REGEXREPLACE(REGEXREPLACE(REGEXREPLACE(UPPER(A1),"[^A-Z]",""),"[AEIOU]","0"),"[^0]","1")=REGEXREPLACE(REGEXREPLACE(REGEXREPLACE(UPPER(JOIN("",(MID(A1,LEN(A1)-ROW(INDIRECT("1:"&LEN(A1)))+1,1)))),"[^A-Z]",""),"[AEIOU]","0"),"[^0]","1"))

```

Three nested `REGEXREPLACE` functions transform it from the original to a string of ones and zeroes. The `JOIN` function is used to reverse the original string so it's nested into the same `REGEXREPLACE` functions to transform it to the reverse string of ones and zeroes. It's a nightmare.
> 0 votes

# Answer
# Excel VBA, 115 Bytes

Anonymous VBE immediate window function that takes input from range `[A1]` and outputs to the VBE immediate window.

```
For i=1To[Len(A1)]:a=Mid([A1],i,1):b=IIf(Instr(1,"AEIOU",a,1),1,IIf(a Like"[A-Za-z]",0,""))&b:Next:?b=StrReverse(b)

```
> 0 votes

# Answer
# Kotlin, 75 bytes

```
filter{it.isLetter()}.map{"aeiou".contains(it,true)}.let{it==it.reversed()}

```

## Beautified

```
filter { it.isLetter() }.map { "aeiou".contains(it, true) }.let { it == it.reversed() }

```

## Test

```
data class Test(val input: String, val output: Boolean)

val tests = listOf(
    Test("Dennis",true),
    Test("Martin",true),
    Test("Martin Ender",true),
    Test("Alex",false),
    Test("Alex A.",true),
    Test("Doorknob",false),
    Test("Mego",false)
)

fun String.f() =
filter{it.isLetter()}.map{"aeiou".contains(it,true)}.let{it==it.reversed()}
fun main(args: Array<String>) {
    for ((input, expected) in tests) {
        val actual = input.f()
        if (actual != expected) throw AssertionError()
    }
}

```

## TIO

TryItOnline
> 0 votes

# Answer
# Julia 0.6, 65 bytes

```
f(s,b=[c in "aeiouAEIOU" for c in s if isalpha(c)])=b==reverse(b)

```

Try it online!
> 0 votes

# Answer
# Pyt, 59 bytes

```
ɬ←ąĐ0↔ą∈⇹6²Ĩ*ž1ᴇ-5²⁺%⁺+ĐĐĐĐ1=⇹5=⇹04Ș9=06Ș+35*=0↔+37*=∨∨∨∨+₽

```

Try it online!

Much of this code is because Pyt is not very good at strings.

Explanation:

```
ɬ               Push "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
←ą              Get input string as an array of characters
Đ               Duplicate the array of characters
0↔              Push 0 and flip the stack
ą               Get the top of the stack as an array of characters
∈               Is each character in the input a letter?
⇹               Swap top two on the stack (input as array of characters)
6²Ĩ             Interpret element-wise as base-36 **
*ž              Remove all non-letters
1ᴇ-             Subtract 10 from each element
5²⁺%            Mod 26
⁺               Increment
+               Let's get rid of that 0
ĐĐĐĐ            Push 4 additional copies of the top of the stack
1=⇹             Is it equal to 1 ('a')
5=⇹04Ș          Is it equal to 5 ('e')
9=06Ș           Is it equal to 9 ('i')
+               Get rid of a 0
35*=            Is it equal to 15 ('o')
0↔              Push 0 and flip the stack
+               Get rid of a 0
37*=            Is it equal to 21 ('u')
∨∨∨∨            OR the arrays
+               Get rid of that last 0
₽               Is the top of the stack a palindrome?

```
> 0 votes

# Answer
# GolfScript, 34 bytes

```
{32|}%.123,97>--{"aeiou"?)!}%.-1%=

```

Try it online!

# Explanation

```
{32|}%                             # Convert to lowercase (Works at least with alpha)
      .123,97>--                   # Keep only lowercase letters
                {"aeiou"?)!}%      # Foreach: is it a vowel?
                             .-1%= # Is it a palindrome?

```
> 0 votes

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


title: Sum the odd square numbers less than N

text:
# Question
Title: Sum the odd square numbers less than N
Write a program or function to **output the sum of the odd square numbers (OEIS #A016754) less than an input `n`**.

The first 44 numbers in the sequence are:

```
1, 9, 25, 49, 81, 121, 169, 225, 289, 361, 441, 529, 625, 729, 841, 961, 1089,
1225, 1369, 1521, 1681, 1849, 2025, 2209, 2401, 2601, 2809, 3025, 3249, 3481,
3721, 3969, 4225, 4489, 4761, 5041, 5329, 5625, 5929, 6241, 6561, 6889, 7225, 7569

```

The formula for the sequence is `a(n) = ( 2n + 1 ) ^ 2`.

### Notes

* Your program's behaviour may be undefined for `n < 1` (that is, all valid inputs are `>= 1`.)

### Test cases

```
1 => 0
2 => 1
9 => 1
10 => 10
9801 => 156849
9802 => 166650
10000 => 166650

```

# Answer
# Jelly, 6 bytes

```
½Ċ|1c3

```

Try it online! or verify all test cases.

### Background

For all positive integers **k**, we have **1² + 3² + ⋯ + (2k - 1)² = k(2k - 1)(2k +1) ÷ 3**.

Since there are **m C r = m! ÷ ((m-r)!r!)** **r**-combinations of a set of **m** elements, the above can be calculated as **(2k + 1) C 3 = (2k + 1)2k(2k - 1) ÷ 6 = k(2k - 1)(2k + 1) ÷ 3.**

To apply the formula, we must find the highest **2k + 1** such that **(2k - 1)² \< n**. Ignoring the parity for a moment, we can compute the highest **m** such that **(m - 1)² \< n** as **m = ceil(srqt(n))**. To conditionally increment **m** if it is even, simply compute **m | 1** (bitwise OR with **1**).

### How it works

```
½Ċ|1c3  Main link. Argument: n

½       Compute the square root of n.
 Ċ      Round it up to the nearest integer.
  |1    Bitwise OR with 1 to get an odd number.
    c3  Compute (2k + 1) C 3 (combinations).

```
> 22 votes

# Answer
## JavaScript (ES6), 30 bytes

```
f=(n,i=1)=>n>i*i&&i*i+f(n,i+2)

```

31 bytes if `f(1)` needs to return zero instead of false:

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

```
> 7 votes

# Answer
## Haskell, 30 bytes

```
f n=sum[x^2|x<-[1,3..n],x^2<n]

```

Surprisingly normal-looking.
> 7 votes

# Answer
# 05AB1E, ~~10~~ 8 bytes

Code:

```
<tLDÉÏnO

```

Explanation:

```
<         # Decrease by 1, giving a non-inclusive range.
 t        # Take the square root of the implicit input.
  L       # Generate a list from [1 ... sqrt(input - 1)].
   DÉÏ    # Keep the uneven integers of the list.
      n   # Square them all.
       O  # Take the sum of the list and print implicitly.

```

Might come in handy: `t;L·<nO`.

Uses **CP-1252** encoding. Try it online!.
> 6 votes

# Answer
# C#, 126 131 bytes

Edited version to conform with the new question:

```
class P{static void Main(){int x,s=0,n=int.Parse(System.Console.ReadLine());for(x=1;x*x<n;x+=2)s+=x*x;System.Console.Write(s);}}

```

Using hardcoded limit:

```
using System;namespace F{class P{static void Main(){int x,s=0;for(x=1;x<100;x+=2)s+=x*x;Console.Write(s);Console.Read();}}}

```
> 4 votes

# Answer
# Jelly, 7

```
’½R²m2S

```

Try it online or try a modified version for multiple values

Shh... Dennis is sleeping...

Thanks to Sp3000 in chat for their help!

### Explanation:

```
’½R²m2S
’           ##  Decrement to prevent off-by-one errors
 ½R²        ##  Square root, then floor and make a 1-indexed range, then square each value
    m2      ##  Take every other value, starting with the first
      S     ##  sum the result

```
> 4 votes

# Answer
# R, ~~38~~ 36 bytes

```
function(n,x=(2*0:n+1)^2)sum(x[x<n])

```

@Giuseppe saved two bytes by moving `x` into the arguments list to save the curly braces. Cool idea!

Ungolfed

```
function(n, x = (2*(0:n) + 1)^2)  # enough odd squares (actually too many)
  sum(x[x < n])                   # subset on those small enough
}

```

Try it online!
> 4 votes

# Answer
# CJam, 15 Bytes

```
qi(mq,2%:)2f#1b

```

Try it online!

Hardcoded 10000 solutions:

Martin's 12 byte solution:

```
99,2%:)2f#1b

```

My original 13 byte solution:

```
50,{2*)2#}%:+

```

Try it online!
> 3 votes

# Answer
# Octave, 23 bytes

```
@(x)(x=1:2:(x-1)^.5)*x'

```

Testing:

```
[f(1); f(2); f(3); f(10); f(9801); f(9802); f(10000)]
ans =
        0
        1
        1
       10
   156849
   166650
   166650

```
> 3 votes

# Answer
# C, ~~51, 50~~ 48 bytes

```
f(n,s,i)int*s;{for(*s=0,i=1;i*i<n;i+=2)*s+=i*i;}

```

Because why not golf in one of the most verbose languages? (Hey, at least it's not Java!)

Try it online!

Full ungolfed program, with test I/O:

```
int main()
{
    int s;
    f(10, &s);
    printf("%d\n", s);
    char *foobar[1];
    gets(foobar);
}

f(n,s,i)int*s;{for(*s=0,i=1;i*i<n;i+=2)*s+=i*i;}

```
> 3 votes

# Answer
## Actually, 7 bytes

```
√K1|3@█

```

Try it online!

Also for 7 bytes:

```
3,√K1|█

```

Try it online!

This uses the same formula as in Dennis's Jelly answer.

Explanation:

```
√K1|3@█
√K       push ceil(sqrt(n))
  1|     bitwise-OR with 1
    3@█  x C 3

```
> 3 votes

# Answer
# MATL, 10 bytes

```
qX^:9L)2^s

```

*EDIT (July 30, 2016): the linked code replaces `9L` by `1L` to adapt to recent changes in the language.*

**Try it online!**

```
q    % Implicit input. Subtract 1
X^   % Square root
:    % Inclusive range from 1 to that
9L)  % Keep odd-indexed values only
2^   % Square
s    % Sum of array

```
> 2 votes

# Answer
# Pyth, 10 bytes

```
s<#Qm^hyd2

```

Test suite

Explanation:

```
s<#Qm^hyd2
    m          Map over the range of input (0 ... input - 1)
       yd      Double the number
      h        Add 1
     ^   2     Square it
 <#            Filter the resulting list on being less than
   Q           The input
s              Add up what's left

```
> 2 votes

# Answer
# Mathcad, 31 "bytes"

Note that Mathcad uses keyboard shortcuts to enter several operators, including the definition and all programming operators. For example, ctl-\] enters a while loop - it cannot be typed and can only be entered using the keyboard shortcut or from the Programming toolbar. "Bytes" are taken to be the number of keyboard operations needed to enter a Mathcad item (eg, variable name or operator).

As I have no chance of winning this competition, I thought I'd add a bit of variety with a direct formula version.
> 2 votes

# Answer
# Racket, 57 bytes

```
(λ(n)(for/sum([m(map sqr(range 1 n 2))]#:when(< m n))m))

```
> 2 votes

# Answer
# Japt `-hx`, ~~6~~ 4 bytes

```
¬o²ó

```

Try it

```
¬o²ó     :Implicit input of integer
¬        :Square root
 o       :Range [0,ceil(¬))
  ²      :Square each
   ó     :Uninterleave
         :Implicit output of sum of last element

```
> 2 votes

# Answer
# Java 8, ~~128~~ ~~119~~ ~~117~~ ~~111~~ 49 bytes

```
n->{int s=0,i=1;for(;i*i<n;i+=2)s+=i*i;return s;}

```

Based on *@Thomas*' C# solution.

**Explanation:**

Try it online.

```
n->{           // Method with integer as both parameter and return-type
  int s=0,     //  Sum, starting at 0
      i=1;     //  Index-integer, starting at 1
  for(;i*i<n;  //  Loop as long as the square of `i` is smaller than the input
      i+=2)    //    After every iteration, increase `i` by 2
    s+=i*i;    //   Increase the sum by the square of `i`
  return s;}   //  Return the result-sum

```
> 1 votes

# Answer
## Haskell, ~~32~~ 31 bytes

```
 n#x=sum[x^2+n#(x+2)|x^2<n]
 (#1)

```

Usage example: `(#1) 9802` -\> `166650`.

Edit: @xnor saved a byte, with a clever list comprehension. Thanks!
> 1 votes

# Answer
# Reng v.3.3, 36 bytes

```
0#ci#m1ø>$a+¡n~
:m%:1,eq^c2*1+²c1+#c

```

Try it here!

## Explanation

### 1: initialization

```
 0#ci#m1ø

```

Sets `c` to `0` (the counter) and the input `I` to the `m`ax.  goes to the next line.

### 2: loop

```
:m%:1,eq^c2*1+²c1+#c

```

`:` duplicates the current value (the squared odd number) and \[I `m` puts `m`ax down. I used the less-than trick in another answer, which I use here. `%:1,e` checks if the STOS \< TOS. If it is, `q^` goes up and breaks out of the loop. Otherwise:

```
         c2*1+²c1+#c

```

`c` puts the counter down, `2*` doubles it, `1+` adds one, and `²` squares it. `c1+#C` increments `c`, and the loop goes again.

### 3: final

```
        >$a+¡n~

```

`$` drops the last value (greater than desired), `a+¡` adds until the stack's length is 1, `n~` outputs and terminates.
> 1 votes

# Answer
## Python, 39 bytes

```
f=lambda n,i=1:+(i*i<n)and i*i+f(n,i+2)

```

If, for `n=1`, it's valid to output `False` rather than `0`, then we can avoid the base case conversion to get 37 bytes

```
f=lambda n,i=1:i*i<n and i*i+f(n,i+2)

```

It's strange that I haven't found a shorter way to get `0` for `i*i>=n` and nonzero otherwise. In Python 2, one still gets 39 bytes with

```
f=lambda n,i=1:~-n/i/i and i*i+f(n,i+2)

```
> 1 votes

# Answer
# PARI/GP, ~~33~~ ~~32~~ 26 bytes

Adapted from Dennis' code:

```
n->t=(1-n^.5)\2*2;(t-t^3)/6

```

My first idea (30 bytes), using a simple polynomial formula:

```
n->t=((n-1)^.5+1)\2;(4*t^3-t)/3

```

This is an efficient implementation, actually not very different from the ungolfed version I would write:

```
a(n)=
{
  my(t=ceil(sqrtint(n-1)/2));
  t*(4*t^2-1)/3;
}

```

An alternate implementation (37 bytes) which loops over each of the squares:

```
n->s=0;t=1;while(t^2<n,s+=t^2;t+=2);s

```

Another alternate solution (35 bytes) demonstrating summing without a temporary variable:

```
n->sum(k=1,((n-1)^.5+1)\2,(2*k-1)^2)

```

Yet another solution, not particularly competitive (40 bytes), using the L2 norm. This would be better if there was support for vectors with step-size indices. (One could imagine the syntax `n->norml2([1..((n-1)^.5+1)\2..2])` which would drop 8 bytes.)

```
n->norml2(vector(((n-1)^.5+1)\2,k,2*k-1))

```
> 1 votes

# Answer
## Python 2, 38 bytes

```
s=(1-input()**.5)//2*2;print(s-s**3)/6

```

Based off Dennis's formula, with `s==-2*k`. Outputs a float. In effect, the input is square rooted, decremented, then rounded up to the next even number.
> 1 votes

# Answer
# Julia, 29 bytes

```
f(n,i=1)=i^2<n?i^2+f(n,i+2):0

```

This is a recursive function that accepts an integer and returns an integer.

We start an index at 1 and if its square is less than the input, we take the square and add the result of recusing on the index + 2, which ensures that even numbers are skipped, otherwise we return 0.
> 1 votes

# Answer
# Julia, 26 bytes

```
x->sum((r=1:2:x-1)∩r.^2)

```

This constructs the range of all odd, positive integers below **n** and the array of the squares of the integers in that range, then computes the sum of the integers in both iterables.

Try it online!
> 1 votes

# Answer
# Oracle SQL 11.2, 97 bytes

```
SELECT NVL(SUM(v),0)FROM(SELECT POWER((LEVEL-1)*2+1,2)v FROM DUAL CONNECT BY LEVEL<:1)WHERE v<:1;

```
> 1 votes

# Answer
# Clojure, 53 bytes

```
#(reduce +(map(fn[x](* x x))(range 1(Math/sqrt %)2)))

```

You can check it here: https://ideone.com/WKS4DA
> 1 votes

# Answer
# Mathematica 30 bytes

```
Total[Range[1,Sqrt[#-1],2]^2]&

```

This unnamed function squares all odd numbers less than the input (`Range[1,Sqrt[#-1],2]`) and adds them.
> 1 votes

# Answer
# PHP, 64 bytes

```
function f($i){$a=0;for($k=-1;($k+=2)*$k<$i;$a+=$k*$k);echo $a;}

```

Expanded:

```
function f($i){
    $a=0;
    for($k=-1; ($k+=2)*$k<$i; $a+=$k*$k);
    echo $a;
}

```

On every iteration of the `for` loop, it will add 2 to k and check if k2 is less than `$i`, if it is add k2 to `$a`.
> 1 votes

# Answer
# R, 60 bytes

```
function(n){i=s=0;while((2*i+1)^2<n){s=s+(2*i+1)^2;i=i+1};s}

```

Does exactly as described in challenge, including returning 0 for the n = 1 case. Degolfed, ';' represents linebreak in R, ignored below:

```
function(n){         # Take input n
i = s = 0            # Declare integer and sum variables
while((2*i+1)^2 < n) # While the odd square is less than n
s = s + (2*i+1)^2    # Increase sum by odd square
i = i + 1            # Increase i by 1
s}                   # Return sum, end function expression

```
> 1 votes

# Answer
# Vyxal `sm`, 5 bytes

```
~∷~∆²

```

Try it Online!

```
~     # range 1..n-1 (due to m flag) filtered by
 ∷    # is odd
  ~   # filtered by
   ∆² # is a perfect square
      # sum is taken by s flag

```
> 1 votes

# Answer
# , 11 bytes

```
3!1 OR>.@%:

```

Pretty straightforward. Uses the Dennis formula.

Attempt This Online!
> 1 votes

# Answer
# FunStack alpha, 46 bytes

```
Sum Greater? @0 takewhile Square Inc Double #N

```

Try it at Replit!

### Explanation

Compute the infinite list of odd square numbers:

```
                  #N  Infinite list of natural numbers
           Double     Each times 2
       Inc            Each plus 1
Square                Each squared

```

Sum those that are less than the input:

```
                takewhile  Take elements from the list while this function is true:
             @0             First program argument
    Greater?                is greater than the list element
Sum                        Sum those elements

```
> 1 votes

# Answer
# Scala, 54 bytes

Golfed version. Try it online!

```
def f(n:Int)=(1 to n by 2).map(x=>x*x).filter(_<n).sum

```

57 bytes version:

```
def f(n:Int)=(1 to n by 2).map(x=>x*x).takeWhile(_<n).sum

```
> 1 votes

# Answer
# Thunno 2 `S-`, 5 bytes

```
ƭRœɗ²

```

### Thunno 2, 7 bytes

```
⁻ƭRœɗ²S

```

Alternatively, a port of Dennis's Jelly answer:

```
ƭṃ1Æ|3c

```

#### Explanation

```
ƭRœɗ²  # Implicit input
       # - flag decrements the input
ƭ      # Square root of (input - 1)
 R     # Pop and push [1..that]
  œɗ   # Only keep odd numbers
    ²  # Square each number in this list
       # S flag sums the list
       # Implicit output

```

```
ƭṃ1Æ|3c  # Implicit input
ƭṃ       # Push ceil(sqrt(input))
  1Æ|    # Bitwise OR with 1
     3c  # Get nCr with r=3
         # Implicit output

```

#### Screenshot
> 1 votes

# Answer
# Python 3, 61 49 bytes

```
lambda n:sum(i*i for i in range(1,n,2)if i*i<n)

```

plenty of savings, thanks for helping me out
> 0 votes

# Answer
# Python 2, 49 bytes

This ended up being shorter than a `lambda`.

```
x=input()
i=1;k=0
while i*i<x:k+=i*i;i+=2
print k

```

**Try it online**

My shortest `lambda`, **53 bytes**:

```
lambda x:sum((n-~n)**2for n in range(x)if(n-~n)**2<x)

```
> 0 votes

# Answer
# Python, 42 38 bytes

```
f=lambda n,i=1:i*i<n and i*i+f(n,i+2)

```
> 0 votes

# Answer
# Ruby, 32 bytes

```
f=->n,i=1{i*i<n ?i*i+f[n,i+2]:0}

```
> 0 votes

# Answer
## Pyke, 7 bytes (noncompetitive)

Add up\_to function which repeats until the rtn is above inp.

```
#}hX)Os

```

Explanation:

```
#   )   -  While rtn < input:
        -   i = 0
 }hX    -    rtn = ((i*2)+1)**2
        -   i+=1
     O  -  rtn[:-1]
      s - sum(^)

```

Try it here!
> 0 votes

# Answer
# Factor, ~~58~~ 57 bytes

```
[| n | n 2 * iota [ 2 * 1 + 2^ ] map [ n < ] filter sum ]

```

Well, this was simpler than I thought!

```
[| n |       ! new local var n
    n 2 *    ! double n
    iota     ! fixnum>range
    [
        2 *  ! double
        1 +  ! + 1
        2^  ! square
    ] map    ! each item in range(0, n*2)
    [
        n <  ! entries over n
    ] filter ! keep-only
    sum ]    ! sum the resulting array

```

Unit tests, if you like:

```
{ 0 }  [ 1  sum-odds-lt ] unit-test
{ 1 }  [ 2  sum-odds-lt ] unit-test
{ 1 }  [ 9  sum-odds-lt ] unit-test
{ 10 } [ 10 sum-odds-lt ] unit-test
{ 156849 } [ 9801 sum-odds-lt ] unit-test
{ 166650 } [ 9802 sum-odds-lt ] unit-test
{ 166650 } [ 10000 sum-odds-lt ] unit-test

```
> 0 votes

# Answer
# bash + bc, 86 bytes

```
s=0
for((n=0;;n++));{
w=`bc<<<"(2*$n+1)^2"`
[ $w -ge $1 ]&&break;
s=$((s+w))
}
echo $s

```

This piece of code is quite self explaining, as it simply sums up the values. It is not quite a magic code, as formatting it properly helps... The stop condition is not in the header of the loop, but after evaluating the step and before adding, since here we have all the values we need without initalising them beforehand.
> 0 votes

# Answer
# Perl 5, ~~51~~ 50 bytes

*-1 byte thanks to TuukkaX.*

Not sure if I can golf this more...

```
$s=0;map{$_%2?$s+=$_**2:()}(1..(<>-1)**.5);print$s

```

`map` checks whether the current value in the array `[1.. sqrt(input-1)]` is odd or even. If it's odd, increase `$s` with the odd number squared.
> 0 votes

# Answer
# Pyt, 6 bytes

```
⁻√ř²ƧƩ

```

Port of FryAmTheEggman's Jelly answer.

Try it online!
> 0 votes

# Answer
# dc, 19 bytes

```
1-v1+2/dd+1+d2-**3/

```

This uses the closed-form formula `⅓k(2k+1)(2k-1)` for the largest `k` such that `(2k-1)² < n`

## Ungolfed version

As a full program:

```
#!/usr/bin/dc -f

?                   # input

1-v1+2/             # k
dd+1+d2-            # k, 2k+1, 2k-1
**3/                # multply

p                   # output

```
> 0 votes

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