title: Is it a lipogram?

text:
# Question
Title: Is it a lipogram?
A lipogram is a block of words that omits a particular symbol. Right now, I am avoiding our fifth symbol of 26 that commonly show up. You should know by now what I am omitting. If not, look up "lipogram" and you will know.

## Your Task

With a char, a blank, and a following string (blanks may show up in this; with only ASCII 32-126 chars) in input, output falsy if this char is in input string, truthy if not. This char that you must look for will always fit in two spans: "A" to "Z" or "a" to "z" (ASCII 65-90, 97-122). Do not distinguish capitals and non-capitals. Also, don't worry about blanks or punctuation symbols. Both programs and functions satisfy. Also, you may split input char and string into two args for programs or functions, and string as first arg is okay.

## Illustrations

### Truthy

```
e This is a lipogram.
a You need to consider other letters too.
E Capitals also count.

```

### Falsy

```
e This sentence is not a lipogram (for e).
t This particular letter is surprisingly hard.
A You don't need to care about any non-alphabetic symbols.

```

---

### Non-lipogrammed version

A lipogram is a series of words that leaves out a letter. I left out the letter "e" above.

Your task is to take a character and a string (which may include spaces) as input, separated by a space or newline, and output falsy if the character is in the string, and truthy otherwise. You may assume the string is composed solely of printable ASCII characters (char codes 32-126). The character will always be in the English alphabet, and there is no difference between lowercase and uppercase. The character will not be a space or symbol. You may write a program or a function. For either, you may take the character and string as separate arguments, and the string may come first.

# Answer
# C, 42 bytes

```
#define f(c,s)!strchr(s,c)&!strchr(s,c^32)

```
> 35 votes

# Answer
## Javascript ES6 ~~34~~ ~~26~~ 23 Bytes

```
x=>!/^(.).*\1/i.test(x)

```

shaved 8 bytes thanks @MartinBüttner
> 26 votes

# Answer
# 05AB1E, ~~7~~ ~~6~~ ~~4~~ 3 bytes

Code:

```
l`-

```

Explanation:

```
l     # Convert both elements to lowercase
 `    # Flatten the array
  -   # Loop over the second line of text and substract each char from the first character
        For example: "abcde""ba"- would result in "cde"

```

Try it online!

Truthy is when the current letter is outputted. Falsy is when nothing is outputted.
> 19 votes

# Answer
# TeaScript, ~~5~~ 3 bytes

```
AµN

```

Aha \o/! I forgot about implicit input! TeaScript will automatically insert `x.` (the input) at the beginning. I can then check if it has the other input (in variable `µ`) and so a NOT (`N`). I guess TeaScript's best advantage here is its implicit input

Try it online

## Explanation

```
  A µ  N
x.A(y).N  // At compile time

x.A // input, has...
(y) // second input
N   // Logical NOT

```
> 14 votes

# Answer
# Japt, ~~12~~ ~~6~~ 4 bytes

```
!VoU

```

Test it online!

@Downgoat's TeaScript answer reminded me that Japt has exactly the same built-in, cutting off a final two bytes.

### How it works

```
       // Implicit: U = input char, V = input string
VoU    // Keep only the chars in V that are equal to U, ignoring case.
!      // Take logical NOT. Returns true if no matches were found, false otherwise.

```
> 12 votes

# Answer
## Bash, ~~16~~ 11 bytes

```
grep -iv $1

```

`-i` is the case-insensitive flag, `-v` inverts (checks for a non-match).

Character must be provided as a command line argument, and the test string on STDIN.

Reduced by 5 bytes with @DigitalTrauma's help!

Sample runs:

```
llama@llama:~$ echo 'This is a lipogram' | ./lipogram.sh e
This is a lipogram.
llama@llama:~$ echo 'This sentence is not a lipogram (for e).' | ./lipogram.sh e

```
> 12 votes

# Answer
## JavaScript (ES6), 29 bytes

```
(c,s)=>!RegExp(c,'i').test(s)

```
> 10 votes

# Answer
## CJam, 6 byte

```
lel(&!

```

Try it online! lel

### Explanation

```
l  e# Read a line of input.
el e# Convert to lower case.
(  e# Pull off the first character.
&  e# Set intersection with the rest of the input.
!  e# Logical NOT.

```
> 10 votes

# Answer
# Python 3, 36

Having to ignore case is surprisingly expensive.

```
lambda a,b:a.lower()not in b.lower()

```

Takes the arguments as (char, string)
> 7 votes

# Answer
## Perl, 11 + 1 = 12 bytes

```
$_=lc!~lc<>

```

Requires the `-p` switch and takes input as `$string\n$letter`

```
$ perl -pe'$_=lc!~lc<>' <<< $'this is a lipogram\ne'
1

```

How it works:

```
            # -p auto reads input into $_ and auto prints at the end
   lc       # lowercase $_
     !~     # Check against regex
       lc<> # Read next line and lowercase it. '=~' will expect the rValue to be
            # a regex and therefore the result from 'lc<>' will be treated as such
$_=         # Assign result ('1' or '') to $_ which will be printed

```
> 7 votes

# Answer
## Pyth, ~~8~~ 7 bytes

```
-rz0rw0

```

Explanation

```
 rw0    -  input().lower()
-       - ^ - V
    rw0 -  input().lower()

```

Thanks @FryAmTheEggman for telling me I can use `-` instead of `!}`

Try it here
> 6 votes

# Answer
# Julia 0.3, ~~22~~ 20 bytes

```
c%s=c&95∉[s...]&95

```

`uppercase` is a *long* word.

### How it works

```
c%s=c&95∉[s...]&95

c%s=                Redefine the binary operator % so it takes a character c and
                    a string s and...
     c&95                Compute lo bitwise AND of c and 95.
                         This casts the character c to uppercase.
          [s...]         Yield the list of the characters of the string s.
                &95      Compute lo bitwise AND of each chararacter and 95.
                         This casts the characters of s to uppercase.
         ∉               Return a Boolean, signaling non-membership.

```
> 6 votes

# Answer
## PowerShell, ~~36~~ ~~32~~ ~~30~~ ~~29~~ 25 bytes

```
param($a,$b)$b-notmatch$a

```

Uses the `-notmatch` operator, and simply outputs `True` or `False`.
> 5 votes

# Answer
## Seriously, 6 bytes

```
,ù,ùíu

```

Try it online!

Takes input as `'string'\n'char'`

Explanation:

```
,ù,ùíu
,ù      get string (lowercase)
  ,ù    get char (lowercase)
    íu  1-based index (0 if not found)

```
> 5 votes

# Answer
## Java, 63 bytes.

```
boolean f(String s,char c){return!s.matches("(?i:.*"+c+".*)");}

```
> 5 votes

# Answer
# O, 8 bytes

```
{_.@_-=}

```

An anonymous function that takes a character and a string.

Try it online.

## Explanation

```
{_.@_-=}

{      }
 _        Lowercase string
  .       Duplicate
   @      Rotate stack
    _     Lowercase character
     -    Remove all instances of the character
      =   Compare to original

```
> 5 votes

# Answer
# MATL, 5 bytes

```
kikm~

```

**Try it online!**

```
k        % take first input (letter) implicitly. Convert to lowercase
ik       % take second input (text). Convert to lowercase
m        % ismember function
~        % negate

```
> 5 votes

# Answer
## Pyke, 7 bytes

```
Dl3+R{!

```

Explanation:

```
D       -     eval_or_not(input()).lower()
 l3     -    ^.swapcase()
   +    -   ^+^
    R   -  rotate 2
     {  -  ^ in ^
      ! - not ^

```
> 4 votes

# Answer
# Retina, 11

```
iA`^(.).*\1

```

I'm not sure what counts as truthy / falsy in Retina, this will echo the line if it is a lipogram for the given character, and it will return the empty string if it isn't.

This will also work for multiline input.

Try it online!
> 4 votes

# Answer
## Minkolang 0.15, 10 bytes

```
$or7Z0Z,N.

```

Try it here.

### Explanation

```
$o            Read in whole input as characters
  r           Reverse stack
   7Z         Lowercase everything
     0Z       Pop top of stack (a) and count how many 'a's are in the stack
       ,      'not' the top of stack
        N.    Output as number and stop.

```
> 4 votes

# Answer
# Jelly, 8 bytes

```
ḢO^O&95P

```

Try it online!

### How it works

```
ḢO^O&95P  Main link. Input: S (string)

Ḣ         Pop the first character of S.
 O        Ordinal; compute its code point.
  ^O      XOR it with the code points of the remaining characters.
    &95   AND each result with 95.
       P  Take the product of the results.

```
> 4 votes

# Answer
## Rust, 75 bytes

```
|c:char,s:&str|!s.to_lowercase().contains(c.to_lowercase().next().unwrap())

```

Biggest score means I win, right? \>\_\<

Try it here.
> 4 votes

# Answer
## Python, 34 bytes

```
lambda c,s:c not in s+s.swapcase()

```

Checks for character `c` being in string `s`, ignoring case by appending a case-swapped copy of `s` to `s`. The negation is done with `not`, which looks lengthy but I don't see better. This is same length:

```
lambda c,s:(c in s+s.swapcase())<1

```

You can't omit the parens or else Python will interpet the expression as a chained three-value inequality of form `_ in _ < _`.

Python 3.5 should allow 33 bytes via set conversions, though I can't test it now.

```
lambda c,s:{*c}-{*s+s.swapcase()}

```
> 4 votes

# Answer
# JavaScript ES6, ~~41~~ 40 bytes

```
x=>!~x.slice(2).search(RegExp(x[0],"i"))

```

Takes the entire string as an argument. I cannot save bytes by accepting two different arguments because then my answer would melt into the other ES6 answer :(
> 3 votes

# Answer
# CJam, 10 bytes

```
{el\ele=!}

```

An anonymous function (block) that takes a character (not a string!) and a string.

Try it online.

## Explanation

```
{el\ele=!}

{        }
 el\el      lowercase both args
      e=    count occurrences of the character
        !   logical not

```
> 3 votes

# Answer
# R, 26 bytes

```
 function(x,y)!grepl(y,x,T)

```

x is the string, y is the letter, the T in the call to grepl makes it case insensitive.
> 3 votes

# Answer
# Jolf, ~~6~~ 7 bytes

So. Many. Sixes. SMS? Well, try it here nonetheless. Replace  with `\x7f`.

```
⌂ MiI'i
⌂_M      match with flags
   i     the input
    I    with another input
     'i  using i as a flag

```
> 3 votes

# Answer
# Vyxal, 6 bytes

```
ɽfhO2<

```

Try it Online!

Accepts one line as input, formatted like the test cases.

How it works:

```
ɽf          # convert input to lowercase and turn into list
  hO        # count the number of times the first item in the list occurs
     2<     # is it less than 2 (should only occur once as the first character)

```
> 3 votes

# Answer
## Ruby, 17 bytes

```
->c,s{/#{c}/i!~s}

```

```
->c,s{  # lambda with two arguments
/#{c}/  # turn the input character into a regexp w/ interpolation
i       # case insensitive
!~      # does not match
s       # input string
}

```
> 2 votes

# Answer
# Mathematica, ~~33~~ 32 bytes

```
StringFreeQ[##,IgnoreCase->1>0]&

```

I love it when ## can be used. Input is string, then char.

Or, a case sensitive version: (11 bytes:)

```
StringFreeQ

```

Yep, just a builtin.
> 2 votes

# Answer
## Batch, 53 bytes

```
@set s=%2
@call set t=%%s:%1=%%
@if %s%==%t% echo 1

```

Accepts input as two command-line arguments. (Quote the second argument if necessary.) Outputs 1 on success, nothing if the first argument is (insensitively) found in the second.
> 2 votes

# Answer
## Haskell, 45 bytes

```
import Data.Char
t=toLower
(.map t).notElem.t

```

Usage example: `( (.map t).notElem.t ) 'a' "You need to consider other letters too"` -\> `True`.

It's a pointfree version of `f c s = notElem (toLower c) (map toLower s)`, i.e. convert letter and string to lowercase and see if the letter is not in the string.
> 2 votes

# Answer
# Java 8 lambda, ~~48~~ 46 bytes

Thanks to @Geobits for pointing out my stupidity and saving me 2 bytes!

```
(String i,char o)->i.split("(?i)"+o).length<2;
```

Splits the string if the sought char is found. Returns true if it is contained, false otherwise.
> 2 votes

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

```
as

```

Try it online!

```
as # Returns 0 for truthy and "true" (?!) for falsey. Takes a list of chars as input
 s # String equals ignore case (vectorising)
a  # Any truthy?

```
> 2 votes

# Answer
## Lua, 47 Bytes

Simply use `string.find()` and a ternary to know if there's a prohibited character in the string.

Takes input via command-line: `lua golf.lua 'e' "This is a Lipogram."`

**Edit: Saved 20 Bytes thanks to @Oleg V. Volkov.**

```
print(not arg[2]:lower():find(arg[1]:lower()))

```
> 1 votes

# Answer
# SpecBAS - 36 bytes

```
1 INPUT a$,b$: ?POS(UP$ a$,UP$ b$)=0

```

Returns 1 (True) if letter is NOT found, 0 (False) if it is. Converting to uppercase with `UP$` save once character vs `LOW$`
> 1 votes

# Answer
## \>\<\> , 42 bytes

```
i:"a"(?\:i:0(?\= ?\70.
.18+" "/   ;n1/;n0/

```

> Overview :
>
> ```
> i:"a"(?\
> .18+" "/
>
> ```
>
> Grabs the first letter, adds space (32) to it if it's not lowercase
>
> ---
>
> ```
> :i:0(?\
>    ;n1/
>
> ```
>
> Grabs the following letters from the input. It compares them to 0 in order to know if it has reached the end of the input, in which case `i` returns -1. In this case it will output 1 and stop.
>
> ---
>
> ```
> = ?\70.
> ;n0/
>
> ```
>
> Compare the current letter to the first one. If they're equal, output 0 and stop. Otherwise, jump back to the beginning of the loop.

You can give it a try on the online interpreter, it nicely illustrates the program flow.
> 1 votes

# Answer
## Hoon, ~~61~~ 56 bytes

```
|*
{a/* b/*}
(lien (trip (cuss b)) (cury test (cuss a)))

```

There are a couple reasons why this is so bad. Unfortunately, Hoon's uppercase/lowercase function is tape -\> cord, so another ++trip call is needed from the result of cuss to turn it back into a list of characters. It also doesn't have a function to test if the list contains a value, only if a function returned yes on any entry.

Hoon has two syntaxs: wide-form and tall-form. Wide-form uses ()'s for grouping such as `?:(a b c)`, while tall-form uses whitespace (either two spaces or a newline) for seperation of twigs. Since newlines count as one byte, using tall-form after runes is smaller although it looks very silly and no one would write it like that.

This entry also abuses Hoon's generic system, wet gates. The `|*` rune is like `|=`, which creates a "function" except that it replaces the type signature with the type of the sample and typedchecks at the callsite instead of definition. Since `|*` and `|=` are the exact same length, but you can omit the type info for the function args, it's smaller to just let the caller provide the type information instead of having `|= {a/tape b/tape}`.

To call it, enter `%+` in the Urbit :dojo, then this snippet, then `"A" "You don't need to care about any non-alphabetic symbols."` (two spaces between those strings!). This is simply a Hoon two-argument function call.
> 1 votes

# Answer
# Befunge 27x2 = 54 bytes

```
 >:~:1+#v_1.@>\:88*`#v_$$
#^_0.@  >\: #^_$~%:0 >84*%-

```

Try It Online

A shorter version that doesn't account for non-alpha characters

```
 >:~:1+#v_1.@_~$84*%
#^_0.@  >\:!#^_\84*%-

```
> 1 votes

# Answer
# GML, 66 bytes

```
return string_pos(string_lower(argument0),string_lower(argument1))

```
> 0 votes

# Answer
# Scala, 50 bytes

```
def f(s:String,c:Char)= !s.matches(s"(?i:.*$c.*)")

```

(Mostly derived from the Java answer)
> 0 votes

# Answer
## Groovy, 58 bytes

```
print args[1].toLowerCase().indexOf(args[0].toLowerCase())

```

Run with:

```
groovy filename.groovy *char* *string*

```
> 0 votes

# Answer
# Oracle SQL 11.2, 68 bytes

```
SELECT TRANSLATE(UPPER(:2),UPPER(:1)||UPPER(:2),UPPER(:1))FROM DUAL;

```

:1 is the char

:2 is the string

Return NULL/empty string as truthy, everything else is falsy.

It translates every character of the string :2 to nothing, which removes them, except for the :1 char.
> 0 votes

# Answer
# DUP, 33 bytes

```
[`32~&a:0[\1-$;$][32~&a;=@|]#%%~]

```

`Try it here.`

Anonymous lambda that takes input from both argument and STDIN and leaves result on stack. Usage:

```
0"asdf"[`32~&a:0[\1-$;$][32~&a;=@|]#%%~]!

```

# Explanation

```
[                                ] {lambda}
 `                                 {get STDIN char}
  32~&                             {uppercase (charcode representation)}
      a:                           {store to a}
        0                          {push 0 to stack as bool}
         [      ][          ]#     {while loop}
          \1-$;$                   {reduce from last string char:}
                  32~&               {uppercase}
                      a;=            {get a==[uppercase char]}
                          @|         {XOR result with bool}
                              %%~  {drop twice, negate TOS (bool)}

```
> 0 votes

# Answer
# C++14, 53 bytes

Based on Josh's answer

As unnamed lambda, assumes `s` to be `std::string` and `c` to be `char`:

```
[](auto s,auto c){return s.find(c)+s.find(c^32)==-2;}

```

Also assumes the length of the strings is below 2^31. If that may be the case, use the safer 58 byte variant:

```
[](auto s,auto c){return s.find(c)==-1&&s.find(c^32)==-1;}

```

Usage:

```
auto f =
  [](auto s,auto c){return s.find(c)+s.find(c^32)==-2;}
;

int main() {
  std::string a = "abcdfg";
  std::cout << f(a,'e') << std::endl;
  std::cout << f(a,'E') << std::endl;
  std::cout << f(a,'a') << std::endl;
  std::cout << f(a,'A') << std::endl;
}

```
> 0 votes

# Answer
# C#, ~~52~~ 51 bytes

```
(C,I)=>{return!I.ToLower().Contains(C.ToLower());};

```

If I could find a way to get rid of ToLower(), I'd save 16 bytes.

One of those cases where I can get rid of the space after return, yay.
> 0 votes

# Answer
# , 19 bytes

```
1=&#[:<;._1 tolower

```

Try it online!
> 0 votes

# Answer
# Go, 77 bytes, using `regexp`

```
import."regexp"
func k(c,s string)bool{b,_:=MatchString("(?i)"+c,s)
return!b}

```

Attempt This Online!

# Go, 78 bytes, using `strings`

```
import."strings"
func f(c,s string)bool{L:=ToLower
return!Contains(L(s),L(c))}

```

Attempt This Online!
> 0 votes

# Answer
# Thunno 2, 3 bytes

```
LẸ-

```

Try it online!

Port of Adnan's 05AB1E answer.

#### Explanation

```
LẸ-  # Implicit input
L    # Lowercase
 Ẹ   # Dump
  -  # Subtract
     # Implicit output

```
> 0 votes

# Answer
**Java, 51 bytes**

```
return(!s.toLowerCase().contains(c.toLowerCase()));

```

Uses s as input and c as char, but c must be of type String.
> -1 votes

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


title: Coprimes up to N

text:
# Question
Title: Coprimes up to N
Given a number `n >= 2`, output all the positive integers less than `n` where `gcd(n, k) == 1` (with `k` being any one of the output numbers). Numbers of this sort are **coprime** to each other.

Example: `10` gives the output `[1, 3, 7, 9]` (in any form you like, as long as the numbers are unambiguously separated and in some sort of list). The list cannot have duplicate entries and doesn't have to be sorted.

More test cases:

```
2 -> [1]
3 -> [1, 2]
6 -> [1, 5]
10 -> [1, 3, 7, 9]
20 -> [1, 3, 7, 9, 11, 13, 17, 19]
25 -> [1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 19, 21, 22, 23, 24]
30 -> [1, 7, 11, 13, 17, 19, 23, 29]

```

We are also not counting numbers above `n` that are coprime to `n`, solely because I'm fairly certain there's infinite solutions.

Also note: Numbers that are coprime to each other are also said to be relatively prime or mutually prime to each other.

# Answer
# Jelly, 3 bytes

```
gÐṂ

```

Try it online!

# How does this work?

```
gÐṂ  - (Monadic) Full program.

g    - Greatest common divisor.
 ÐṂ  - Keep the elements with minimum link value (i.e. those with GCD == 1)
       Note that this automatically creates the range [1, input] (inclusive).

```

## Proof of validity

Since we want to extract the coprimes only, the minimum value of the Greatest-Common-Divisors list *has* to be **1** for the `ÐṂ` trick to work. Let's prove that (in two different methods):

1. The implicitly generated range, \\$\[1, \text{input}\]\\$ contains \\$1\\$ and \\$\gcd(1, x) = 1\\:\\:\forall\\:\\:x \in \mathbb{Z}^{\*}\\$. The greatest common divisor is always a strictly positive integer, hence \\$1\\$ is guaranteed to occur and will always be the minimum value.
2. Two consecutive positive integers are always coprime. Consider \\$x, y \in \mathbb{Z}^{\*}\\$, with \\$y = x + 1\\$. Then we take another positive integer \\$k\\$ such that \\$k \mid x\\$ and \\$k \mid y\\$.

This implies that \\$k \mid (y - x)\\$, so \\$k \mid (x + 1 - x)\\$, thus \\$k \mid 1\\$. The only positive integer to divide \\$1\\$ is \\$1\\$ itself, so it is guaranteed to appear in the list and will always be the minimum value.
> 19 votes

# Answer
# Python 2, ~~61~~ 47 bytes

```
lambda n:[k/n for k in range(n*n)if k/n*k%n==1]

```

Try it online!

### Background

Consider the ring \\$(Z\_n, +\_n, \cdot\_n)\\$. While this ring is usually defined using residue classes modulo \\$n\\$, it can also be thought of as the set \\$Z\_n = \\{0, \dots, n - 1\\}\\$, where the addition and multiplication operators are defined by \\$a +\_n b = (a + b)\\:\\%\\: n\\$ and \\$a \cdot\_n b = a \cdot b\\:\\%\\: n\\$, where \\$+,\\:\cdot\text{, and } \\%\\$ denote the usual addition, multiplication, and modulo operators over the integers.

Two elements \\$a\\$ and \\$b\\$ of \\$Z\_n\\$ are called mutual multiplicative inverses modulo \\$n\\$ if \\$a \cdot\_n b = 1\\:\\%\\:n\\$. Note that \\$1\\:\\%\\:n = 1\\$ whenever \\$n \> 1\\$.

Fix \\$n \> 1\\$ and let \\$a\\$ be a coprime of \\$n\\$ in \\$Z\_n\\$. If \\$a \cdot\_n x = a \cdot\_n y\\$ for two elements \\$x\\$ and \\$y\\$ of \\$Z\_n\\$, we have that \\$a \cdot x\\:\\%\\:n = a \cdot y\\:\\%\\:n\\$. This implies that \\$a \cdot (x - y)\\:\\%\\:n = a \cdot x\\:\\%\\:n - a \cdot y\\:\\%\\:n = 0\\$, and we follow that \\$n \mid a \cdot (x - y)\\$, i.e., \\$n\\$ divides \\$a \cdot (x - y)\\$ evenly. Since \\$n\\$ shares no prime divisors with \\$a\\$, this means that \\$n \mid x - y\\$. Finally, because \\$-n \< x - y \< n\\$, we conclude that \\$x = y\\$. This shows that the products \\$a \cdot\_n 0, \dots, a \cdot\_n (n - 1)\\$ are all different elements of \\$Z\_n\\$. Since \\$Z\_n\\$ has exactly \\$n\\$ elements, one (and exactly one) of those products must be equal to \\$1\\$, i.e., there is a *unique* \\$b\\$ in \\$Z\_n\\$ such that \\$a \cdot\_n b = 1\\$.

Conversely, fix \\$n \> 1\\$ and let \\$a\\$ be an element of \\$Z\_n\\$ that is *not* coprime to \\$n\\$. In this case, there is a prime \\$p\\$ such that \\$p \mid a\\$ and \\$p \mid n\\$. If \\$a\\$ admitted a multiplicative inverse modulo \\$n\\$ (let's call it \\$b\\$), we'd have that \\$a \cdot\_n b = 1\\$, meaning that \\$a \cdot b\\:\\%\\:n = 1\\$ and, therefore, \\$(a \cdot b - 1)\\:\\%\\:n = a \cdot b\\:\\%\\:n - 1 = 0\\$, so \\$n \mid a \cdot b - 1\\$. Since \\$p \mid a\\$, we follow that \\$p \mid a \cdot b\\$. On the other hand, since \\$p \mid n\\$, we also follow that \\$p \mid a \cdot b - 1\\$. This way, \\$p \mid (a \cdot b) - (a \cdot b - 1) = 1\\$, which contradicts the assumption that \\$p\\$ is a prime number.

This proves that the following statements are equivalent when \\$n \> 1\\$.

* \\$a\\$ and \\$n\\$ are coprime.
* \\$a\\$ admits a multiplicative inverse modulo \\$n\\$.
* \\$a\\$ admits a *unique* multiplicative inverse modulo \\$n\\$.

### How it works

For each pair of integers \\$a\\$ and \\$b\\$ in \\$Z\_n\\$, the integer \\$k := a \cdot n + b\\$ is unique; in fact, \\$a\\$ and \\$b\\$ are quotient and remainder of \\$k\\$ divided by \\$n\\$, i.e., given \\$k\\$, we can recover \\$a = k/n\\$ and \\$b = k\\:\\%\\: n\\$, where \\$/\\$ denotes *integer* division. Finally, since \\$a ≤ n - 1\\$ and \\$b ≤ n - 1\\$, \\$k\\$ is an element of \\$Z\_{n^2}\\$; in fact, \\$k ≤ (n - 1) \cdot n + (n - 1) = n^2 - 1\\$.

As noted above, if \\$a\\$ and \\$n\\$ are coprime, there will be a unique \\$b\\$ such that \\$a \cdot b\\:\\%\\:n = 1\\$, i.e., there will be a unique \\$k\\$ such that \\$k / n = a\\$ and \\$k / n \cdot k\\:\\%\\:n = (k / n) \cdot (k\\:\\%\\:n)\\:\\%\\:n = 1\\$, so the generated list will contain \\$a\\$ exactly once.

Conversely, if \\$a\\$ and \\$n\\$ are *not* coprime, the condition \\$k / n \cdot k\\:\\%\\:n = 1\\$ will be false for all values of \\$k\\$ such that \\$a = k / n\\$, so the generated list will *not* contain \\$a\\$.

This proves that the list the *lambda* returns will contain all of \\$n\\$'s coprimes in \\$Z\_n\\$ exactly once.
> 67 votes

# Answer
# Jelly, 4 bytes

```
gRỊT

```

Try it online!

### How it works

```
gRỊT  Main link. Argument: n

 R    Range; yield [1, ..., n].
g     Compute the GCD of n and each k in [1, ..., n].
  Ị   Insignificant; return 1 for GCDs less or equal to 1.
   T  Truth; yield the indices of all truthy elements.

```
> 24 votes

# Answer
## Mathematica, 25 bytes

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

```

Slightly weird output format, where each result is wrapped in a separate list, e.g. `{{1}, {3}, {7}, {9}}`. If that's not okay, I've got two solutions at 30 bytes:

```
Select[Range[x=#],#~GCD~x<2&]&
#&@@@Range@#~GCD~#~Position~1&

```

Mathematica actually has `CoprimeQ` but that's way too long.
> 14 votes

# Answer
# Python, ~~93~~ ~~82~~ 74 bytes

```
f=lambda a,b:f(b,a%b)if b else a<2
lambda c:[i for i in range(c)if f(i,c)]

```

`f` recursively checks for coprimes, and the second lambda generates them. Outputs a list.
> 10 votes

# Answer
# 2sable, 4 bytes

Code:

```
ƒN¿–

```

Explanation:

```
ƒ       # For N in the range [0, input]..
 N¿     #   Compute the GCD of N and the input
   –    #   If 1, print N with a newline

```

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

# Answer
# Actually, 8 bytes

```
;╗R`╜┤`░

```

Try it online!

Explanation:

```
;╗R`╜┤`░
  R`  `░  elements of range(1, n+1) where
;╗  ╜     n and the element
     ┤    are coprime

```
> 7 votes

# Answer
# MATL, 7 bytes

```
:GZd1=f

```

Try it online!
> 6 votes

# Answer
# JavaScript (ES6), ~~64~~ 61 bytes

*Saved 3 bytes thanks to @user81655*

```
n=>[...Array(n).keys()].filter(b=>(g=a=>b?g(b,b=a%b):a<2)(n))

```

### Test snippet

```
f=n=>[...Array(n).keys()].filter(b=>(g=a=>b?g(b,b=a%b):a<2)(n))

for(var i = 2; i < 50; i++) console.log(i + ":", `[${ f(i) }]`);
```
> 6 votes

# Answer
# MATLAB/Octave, 22 bytes

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

```

Try it online!
> 6 votes

# Answer
## Jellyfish, ~~19~~ 18 bytes

```
p
[#
`B
&~xr1
NnEi

```

This works by computing the prime factorization of every number in the range and checking whether it intersects that of the input (Jellyfish doesn't have a gcd builtin yet). For golfing reasons, the output is in descending order. Try it online!

## Explanation

First off, `i` is evaluated input; for input `10`, the value of the `i`-cell is `10`.

```
r1
i

```

Here `r` (range) is applied to the input and 1. Because the input is greater than 1, the range is in descending order; for input `10`, this gives `[9 8 7 6 5 4 3 2 1]`.

```
[#
`B
&~x
Nn

```

This part is one big function, which is evaluated on `i` and the above range.

```
~x
n

```

Intersection (`n`) of prime factors (`x`).

```
&~x
Nn

```

Is it empty? (`N`)

```
`
&~x
Nn

```

Thread to level 0, testing for each element of the range.

```
[#
`B
&~x
Nn

```

Filter (`#`) the range with respect to this list of booleans. The function produced by `[` wants to use the argument to `#` as its own argument, so we put a `B` to block `#` from getting any arguments. Otherwise, the value of the `~`-cell would be used as the argument of the big function. Finally, `p` prints the result.
> 6 votes

# Answer
# Stacked, noncompeting, ~~24~~ 21 bytes

Saved 3 bytes, inspired by Borsunho's ruby. (`1 eq` to `2<`)

```
{!n:>1+:n gcd 2<keep}

```

Try it here!

This is an n-lambda that takes a single argument and yields the array.

```
{!n:>1+:n gcd 2<keep}
{!                  }  n-lambda
  n                    push n
   :>                  range [0, n)
     1+                range [1, n]
       :               duplicate
        n gcd          element-wise gcd with n
              2<       element-wise equality with 1
                       this yields the range [1, n] and a boolean mask of coprime numbers
                keep   then, we simply apply the mask to the range and keep coprimes.

```
> 5 votes

# Answer
## CJam, 14 bytes

```
{:X{Xmff%:*},}

```

Try it online!

### Explanation

We don't need to check all possible divisors of `a` and `b` to test whether they're coprime. It's sufficient to look at whether any of the prime factors of `b` divides `a`.

```
:X     e# Store the input in X.
{      e# Filter the list [0 1 ... X-1] by the results of this block...
  Xmf  e#   Get the prime factors of X.
  f%   e#   Take the current value modulo each of those prime factors.
  :*   e#   Multiply the results. Iff any of them divide the current
       e#   value, there's a 0 in the list, and the result of the product
       e#   is also 0, dropping the value from the resulting list.
},

```
> 5 votes

# Answer
# Mathematica, 26 bytes

```
Pick[r=Range@#,r~GCD~#,1]&

```
> 5 votes

# Answer
# Dyalog APL, 10 bytes.

```
0~⍨⍳×1=⊢∨⍳

```

Explanation (input `n`):

```
0~⍨⍳×1=⊢∨⍳
         ⍳ - 1 ... n (Thus, ⎕IO is 1)
       ⊢∨  - Each GCD'd by n
     1=    - Test equality with 1 on each element
   ⍳×      - multiplied by its index
0~⍨        - without 0.

```
> 4 votes

# Answer
# Perl 6, 20 bytes

```
{grep 2>* gcd$_,^$_}

```
> 4 votes

# Answer
# Julia 0.5, 23 bytes

```
!n=1÷gcd.(1:n,n)|>find

```

Try it online!
> 4 votes

# Answer
# Brachylog, ~~16~~ 13 bytes

```
>.$p'(e:A*?),

```

This is a function that takes *N* as input, and generates all integers less than and coprime to it.

Try it online! As is often the case in Brachylog, this has had extra code added to make the function into a full program; Brachylog's interpreter, if given a function rather than a full program, will run it but not print the output, which means you can't really observe its workings.

Explanation:

A Brachylog program is a chain of constraints; typically, the LHS of one constraint is the RHS of the next.

```
>.$p'(e:A*?),
>              The input is greater than
 .             the output, whose
  $p           prime factorisation does
    '(     )   not obey the following constraint:
      e        it has an element which
       :A*     can be multiplied by something to
          ?    produce the input.
            ,  (This comma turns off an unwanted implicit constraint.)

```

Golfed down three characters by realising there's no reason to check to see if the common factor (which is already known to be a prime factor of the output) is a *prime* factor of the input. We already know it's prime, so we can just check if it's a factor. I'm pleasantly surprised here that `:A*?` doesn't send the interpreter into an infinite loop *and* doesn't allow a non-integer value for *A*, but as the interpreter does what I want, I'll take it.
> 4 votes

# Answer
# Japt `-f`, ~~9~~ ~~8~~ ~~5~~ 2 bytes

```
jN

```

Try it

* 2 bytes saved thanks to ETH pointing out a brainfart, which led to another byte saved.
> 4 votes

# Answer
# Mathematica, 33 bytes

```
xSelect[Range@x,x~CoprimeQ~#&]

```

Contains U+F4A1
> 3 votes

# Answer
# Haskell, 27 bytes

```
f n=[k|k<-[1..n],gcd n k<2]

```

Try it online!
> 3 votes

# Answer
# memes, 11 bytes

Uses UTF-8 encoding.

```
d`}}]i=1?ip

```

Explanation:

```
d     Set program to not output result
`}    Loop next input-times
}]i   GCD of input and loop index
=1?   Is it equal to 1? If yes,
ip    Print out loop index

```

`}` accesses the next input item, but last input is looped through when given, so inputting `6` will result as `6 6 6 6 6 ...` in STDIN, making it possible for reading two outputs from one.
> 3 votes

# Answer
# 05AB1E, 3 bytes

```
Lʒ¿

```

Try it online!

Has new features.
> 3 votes

# Answer
# Ruby, ~~36~~34

```
->n{n.times{|i|p i if i.gcd(n)<2}}

```

Admittedly, this isn\`t a very *inspired* answer.

2 bytes saved thanks to Conor O'Brien.
> 2 votes

# Answer
# Python 3, 60 bytes

Imports gcd instead of writing a new lambda for it. Golfing suggestions welcome. Try it online!

```
import math
lambda c:[i for i in range(c)if math.gcd(c,i)<2]

```
> 2 votes

# Answer
# Julia, 30 bytes

```
n->filter(x->(gcd(n,x)<2),1:n)

```

Anonymous function. `filter` removes elements from a list that aren't truthy according to a function.

In this case, the function is `x->(gcd(n,x)<2)` (true if the gcd of the input and the list element is less than 2). The list is the range `1:n`.
> 2 votes

# Answer
# PARI/GP, 27 bytes

```
n->[k|k<-[1..n],gcd(k,n)<2]

```

This uses the set-notation introduced in version 2.6.0 (2013). In earlier versions, four more bytes were needed:

```
n->select(k->gcd(k,n)<2,[1..n])

```

would be needed.
> 2 votes

# Answer
# 05AB1E, 4 bytes

```
GN¿–

```

Try it online!

How it works

```
     # implicit input
G    # for N in range(1..input)
 N   # push N
  ¿  # gcd(input, N)
   – # if 1, print N

```
> 2 votes

# Answer
# C (gcc), 54 bytes

```
k;f(n){for(k=0;++k/n<n;k/n*k%n-1||printf("%u ",k/n));}

```

This is a port of my Python answer.

Try it online!
> 2 votes

# Answer
# Whispers v2, 65 bytes

```
> Input
> 1
>> (1]
>> L⊓1
>> L=2
>> Select∘ 4 5 3
>> Output 6

```

Try it online!

Uses the recently implemented `Select∘` command.

## How it works

The entire program is built from lines **4**, **5** and **6**

```
>> L⊓1
>> L=2
>> Select∘ 4 5 3

```

This is the first use of any of the three `Select` statements, this time using the `Select∘` statement. All forms of the `Select` statements take **n** line references as arguments. The last number references the array to select from (let's say \\$A\\$), and the others reference the functions to iterate over that array (i.e the array of functions, \\$B\\$). However, they differ as follows:

* `Select∧` \- Only select elements which are truthy under all functions in \\$B\\$:

$$R := \[x \in A \\: | \\: f(x) \top, \forall f \in B\]$$

* `Select∨` \- Only select elements which are truthy under any function in \\$B\\$

$$R := \[x \in A \\: | \\: f(x) \top, \exists f \in B\]$$

* `Select∘` \- Only select elements which, when all functions in \\$B\\$ are composed together, are truthy under this new function:

$$\text{Let }B := \[f(x), g(x), h(x)\]$$ $$R := \[x \in A \\: | \\: h(g(f(x))) \\: \top\]$$

In this program, we can define \\$A := \[1, 2, ..., \alpha-1, \alpha\]\\$, where \\$\alpha\\$ is the input. We then define line **4** (`>> L⊓1`) as \\$f(x) = \gcd(x, \alpha)\\$ and line **5** (`>> L=2`) as \\$g(x) := (x = 1)\\$. Finally, we can define \\$B = \[f(x), g(x)\]\\$. This sets us up for the select statement as shown above.

When we encounter the `Select∘` statement, we take \\$R\\$ (the final array) as defined by the third relationship above. To make things slightly easer, we'll define

\begin{align} h(x) & := g(f(x)) \\ & := gcd(x, \alpha) = 1 \end{align}

\\$R\\$ is then equal to the array where \\$\forall x \in R\\$, \\$h(x) \\: \top\\$. Finally, on the last line, we output \\$R\\$.

### Shorter version, 56 bytes

```
> Input
> 1
>> (1]
>> L⟂1
>> Select∘ 4 3
>> Output 5

```

Try it online!

This is much less interesting as it uses the co-prime builtin. In this case, any of the three select statements can be used.
> 2 votes

# Answer
# Vyxal, 5 bytes

```
'?ġ1=

```

Try it Online!

Explanation:

```
       # Implicit input
'      # Apply function for n in range [0,input) and filter:
 ?     #   Input
  ġ    #   GCD of input and current number
   1=  #   Equal to 1?
       # Implicit output

```
> 2 votes

# Answer
## JavaScript (Firefox 30-57), 53 bytes

```
n=>[for(i of Array(n*n).keys())if(i*(i=i/n|0)%n==1)i]

```

Port of @Dennis's amazing Python answer. 60 bytes in ES6:

```
n=>[...Array(n*n)].map((_,i)=>i/n|0).filter((i,j)=>i*j%n==1)

```

Similar idea of looking for the multiplicative inverse, also 60 bytes in ES6:

```
n=>[...Array(n).keys()].filter((i,_,a)=>a.some(j=>i*j%n==1))

```
> 1 votes

# Answer
# Pyth, 5 bytes

```
x1iLQ

```

Try it online!

## How it works

Note that Pyth uses 0-indexing.

```
x1iLQ   Q = eval(input())

x1iLQQ  implicit Q at the end
  iLQQ  [gcd(Q,0), gcd(Q,1), ..., gcd(Q,Q-1)]
x1      all occurences of 1 in the above list (return their indices)

```
> 1 votes

# Answer
# Husk, ~~7~~ 6 bytes

```
§foε⌋ḣ

```

-1 thanks @Leo!

Try it online!

### Explanation

```
        -- implicit input N
§f   ḣ  -- filter the range [1..N] with
  oε⌋   --   is gcd(N,·) at most 1

```
> 1 votes

# Answer
# C (gcc), 99 bytes

```
#include<stdio.h>
g(a,b){return b>0?g(b,a%b):a;}c(n,i){for(i=1;i<n;i++)g(n,i)<2?printf("%i ",i):0;}

```

Try it online!
> 1 votes

# Answer
# Java 8, 98 bytes

```
import java.util.*;n->{Set r=new HashSet();for(int i=0;++i/n<n;)r.add(i/n*i%n==1?i/n:1);return r;}

```

Port of *@Dennis*' amazing Python answer.

**Explanation:**

Try it here.

```
import java.util.*;     // Required import for Set and HashSet

n->{                    // Method with integer parameter and Set return-type
  Set r=new HashSet();  //  Result-Set
  for(int i=0;          //  Index-integer (starting at 0)
      ++i/n<n;)         //  Loop as long as `i/n` is smaller than `n`
                        //  (starting `i` at 1 by first increasing it by 1 with `++i`)
    r.add(i/n           //   If `i/n`,
          *i%n          //   multiplied by `i` modulo-`n`,
              ==1?      //   is exactly 1:
           i/n          //    Add `i/n` to the Set
          :             //   Else:
           1            //    Add 1 to the Set
  );                    //  End of loop
  return r;             //  Return the result-Set
}                       // End of method

```
> 1 votes

# Answer
# Gaia, 2 bytes

```
S⁇

```

Try it online!

I seem to have outgolfed myself.

```
S⁇  - Full program.

 ⁇  - Filter-Keep (operates on the automatically generated range).
S   - Check if the input and the current element are coprime.

```
> 1 votes

# Answer
# C ~~177~~ ,  ~~150~~  , ~~135~~ , 102 bytes

Not very golfy but...

```
p,i,t,x,y,N;f(n){
int A[9]={};
for(i=0,N=n;p<n;n/=p){
for(p=2+(n&1);n%p;)p+=2;
A[i++]=p;
}
for(y=0;y++<N;){
for(i=t=0;x=A[i++];)
t|=!(y%x);
if(!t)printf("%d ",y);
}
}

```

EDIT: one line 150

```
p,i,t,x,y,N;f(n){int A[9]={};for(i=0,N=n;p<n;n/=A[i++]=p)for(p=2+(n&1);n%p;)p+=2;for(y=0;y++<N;){for(i=t=0;x=A[i++];)t|=!(y%x);printf("\0 %d"+!t,y);}}

```

EDIT2:

```
f(n){int p,t,x,i=0,y=0,N=n,A[9]={};for(;p<n;n/=A[i++]=p)for(p=2;n%p;)p++;for(;y++<N;printf("\0 %d"+!t,y))for(i=t=0;x=A[i++];)t|=y%x<1;}

```

Stores array of primefactors of N,
Then prints numbers \< N that don't divide those.

EDIT3:
Got rid of Array, recalulating primefactors instead

```
f(n){int p,t,i=0,N=n;for(;i++<N;printf("\0 %d"+!t,i))for(n=N,p=t=0;p<n;n/=p,t|=i%p<1)for(p=1;n%++p;);}

```

Try it online!
> 1 votes

# Answer
# Funky, 59 bytes

```
g=(a,b)=>b?g(b,a%b):(a>1)ort[#t]=i
f=n=>fort={}n>i++g(n,i)t

```

This defines the function `f`, which generates a list of all co-primes from `1` to `n`.

Try it online!
> 1 votes

# Answer
# Pari/GP, 28 bytes

```
n->[x|x<-[0..n],gcd(x,n)==1]

```

Try it online!
> 1 votes

# Answer
# SNOBOL4 (CSNOBOL4), 149 bytes

```
	DEFINE('G(A,B)')
	N =INPUT
I	X =X + 1
	EQ(X,N)	:S(END)
	K =G(N,X)
	OUTPUT =EQ(K,1) X :(I)
G	T =REMDR(A,B)
	A =B
	B =T
	G =EQ(B) A	:F(G)S(RETURN)
END

```

Try it online!

Uses the Euclidean algorithm in the function `G` to calculate the GCD; prints values with newlines between them.

```
	DEFINE('G(A,B)')		;*let the interpreter know a function G is available
	N =INPUT			;*read input
I	X =X + 1			;*increment step
	EQ(X,N)	:S(END)			;*if X==N, end
	K =G(N,X)			;*K =GCD(N,X)
	OUTPUT =EQ(K,1) X :(I)		;*if K==1, output X. goto I
G	T =REMDR(A,B)			;*function body: euclidean algorithm
	A =B
	B =T
	G =EQ(B) A	:F(G)S(RETURN)	;*if B==0, G=A and return.
END

```
> 1 votes

# Answer
# J, 16 Bytes

```
C=:I.@(1:=]+.i.)

```

C for coprime.

### How it works:

```
C=:                | Define the verb C
             i.    | Integers between 0 and n-1 inclusive
          ]+.      | GCD with n. Gets applied to each element of i.n
       1:=         | Test whether each element of the array is 1. If it is, put 1, otherwise 0
   I.              | Return the indexes of the 1s. If there are none (i.e., on input 1) returns 0.

```

Parenthesis and @ are just so it gets executed in the right order.

Step by step example:

```
    (]+.i.) 10
10 1 2 1 2 5 2 1 2 1

    (1:=]+.i.) 10
0 1 0 1 0 0 0 1 0 1

    I.@(1:=]+.i.) 10
1 3 7 9

    C 10
1 3 7 9

```
> 1 votes

# Answer
# Wonder, 35 bytes

```
@(!>@=1len inx 'fac#0fac#1).'rng1#0

```

Usage:

```
(@(!>@=1len inx 'fac#0fac#1).'rng1#0)3

```

Basically filters over a range from 1 to the input with a predicate:

* Find all factors of both the current mapped item and the input.
* Find the intersection of both arrays.
* Check if the result is of length 1. If the 2 numbers are coprime, then their factors' intersection set should only contain 1.
> 0 votes

# Answer
# Julia 1.0, 33 bytes

```
(n)->[k for k=1:n if gcd(n,k)==1]

```

Try it online!
> 0 votes

# Answer
# Scala, 35 bytes

```
n=>BigInt(1)to n filter(_.gcd(n)<2)

```

Try it in Scastie!
> 0 votes

# Answer
# MMIX, 76 bytes (19 instrs)

```
void __mmixcall coprimes(octa n,
                         void *d, void (*__mmixcall f)(void *d, octa i));

```

(jelly xxd)

```
00000000: fe03 0004 c104 0000 f701 0000 2704 0401  “¤¡¥Ḋ¥¡¡ẋ¢¡¡'¥¥¢
00000010: 5a04 0003 f604 0003 f800 0000 c105 0400  Z¥¡¤ẇ¥¡¤ẏ¡¡¡Ḋ¦¥¡
00000020: c106 0000 1e06 0605 c106 0500 fe05 0006  Ḋ©¡¡œ©©¦Ḋ©¦¡“¦¡©
00000030: 5b05 fffd 2706 0601 4306 fff5 c106 0100  [¦”’'©©¢C©”ṫḊ©¢¡
00000040: c107 0400 bf05 0200 f1ff fff1            Ḋ¬¥¡Ḃ¦£¡ȯ””ȯ

```

Disassembly and explanation

```
coprimes    GET    $3,rJ        // savedj = rJ
            SET    $4,$0        // i = n
            PUT    rD,0         // zero out hidiv register
0H          SUBU   $4,$4,1      // loop: i--
            PBNZ   $4,1F        // iflikely(i) goto continuation
            PUT    rJ,$3        // rJ = savedj
            POP    0,0          // return
1H          SET    $5,$4        // continuation: p = i
            SET    $6,$0        // q = n
1H          DIVU   $6,$6,$5     // gcd: q:rR = rD:q /% p
            SET    $6,$5        // q = p
            GET    $5,rR        // p = rR
            PBNZ   $5,1B        // iflikely(p) goto gcd
            SUBU   $6,$6,1      // q--
            BZ     $6,0B        // if(!q) goto loop
            SET    $6,$1        // fa1 = d
            SET    $7,$4        // fa2 = i
            PUSHGO $5,$2,0      // f(fa1,fa2)
            JMP    0B           // goto loop

```

I don't have a good way to output a sequence, so I just went with the tried and true callback method. Works for any `n` from \\$1\\$ to \\$2^{63}-1\\$.
> 0 votes

# Answer
# Factor, 40 bytes

```
[ dup iota [ gcd nip 1 = ] with filter ]

```

Try it online!
> 0 votes

# Answer
# Arturo, 31 bytes

```
$->n[select..1n'x->1=gcd@[x,n]]

```

Try it
> 0 votes

# Answer
# Nekomata, 4 bytes

```
rG1Ĩ

```

Attempt This Online!

```
r       Range from 0 to input - 1
 G      GCD with input
  1Ĩ    Find indices of 1s (0-indexed)

```
> 0 votes

# Answer
# Thunno 2 `v`, 3 bytes

```
æĠḅ

```

Try it online!

#### Explanation

```
æĠḅ  # Implicit input
æ    # Filter (implicit cast to range) by:
 Ġ   #  GCD of this number and the input
  ḅ  #  Equals one?
     # Implicit output

```
> 0 votes

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


title: Guess the song title

text:
# Question
Title: Guess the song title
I have this problem where I listen to so much music that I can never remember what songs are called. But even if I remember the lyrics, I won't always know the song's name. But lucky for me, there's a pretty neat formula to determine¹ the title of a song just based on its lyrics.

I'll define the way a song title can be guessed as the line repeated in its lyrics the most times. If multiple lines are repeated the same number of times, choose the shortest of them. If multiple lyrics both occur the same number of times and are of equal length, you may choose any of them.

Given an input of a multiline string where each line is a lyric (you may take input as a list of lines), output the predicted title of the song, using the method outlined above.

For example, say this totally real song was stuck in my head and I couldn't remember its name:

```
Hello, world
Hello, world
I just got to say it, hello world
Goodbye, world
Goodbye, world
Goodbye

```

I can figure using this formula that the song's title is "Hello, world".

You may assume that the input string will contain no empty lines.

## Test cases:

Links go to pastebins of the lyrics, with any `"` removed.

---

This is , so shortest code in bytes wins.

¹ Accuracy not guaranteed. No refunds.

# Answer
> 12 votes
# 05AB1E, 3 bytes

```
é.M

```

Input as a list of lines.

Try it online or verify all test cases.

**Explanation:**

```
é    # Sort the (implicit) input-list by their length (shortest to longest)
 .M  # Pop and leave the (first/shortest) most frequent line
     # (which is output implicitly as result)

```

# Answer
> 11 votes
# Vyxal, 4 bytes

```
Þṡ∆M

```

Try it Online!

```
Þṡ   # Sort by length
  ∆M # Get the most common item (order overrides repetitions)

```

# Answer
> 10 votes
# Excel (ms365), 74 bytes

Formula in `B1`:

`=LET(x,TEXTSPLIT(A1,"
"),@SORTBY(x,MAP(x,LAMBDA(y,SUM(-(x=y)))),,LEN(x),))`

* `TEXTSPLIT(A1,"
")` \- Split input in an horizontal array called 'x';
* `SORTBY(x,MAP(x,LAMBDA(y,SUM(-(x=y)))),,LEN(x),)` \- 1st Sort by count, then by length (both ascending by default);
* `@` \- Use implicit intersection to only return the 1st element in the resulting array.

# Answer
> 8 votes
# Python, ~~49~~ 43 bytes

```
lambda a:max(sorted(a,key=len),key=a.count)

```

Attempt This Online!

Takes input as a list of lines

# Answer
> 6 votes
# , 28 17 bytes

```
{.@\:%@#&>+1#.=/~

```

Try it online!

*-11 thanks to l4m2's idea. Also thanks to l4m2 for pointing out an improvement!*

Consider:

```
Hello, world
Hello, world
I just got to say it, hello world
Goodbye, world
Goodbye, world
Goodbye

```

In J we take the input as a list of boxed strings:

```
┌────────────┬────────────┬─────────────────────────────────┬──────────────┬──────────────┬───────┐
│Hello, world│Hello, world│I just got to say it, hello world│Goodbye, world│Goodbye, world│Goodbye│
└────────────┴────────────┴─────────────────────────────────┴──────────────┴──────────────┴───────┘

```
* `=/~` Create an equality table to see which lines equal other lines:

```
1 1 0 0 0 0
1 1 0 0 0 0
0 0 1 0 0 0
0 0 0 1 1 0
0 0 0 1 1 0
0 0 0 0 0 1

```
* `1#.` Sum the rows (resulting length is now equal to input length):

```
2 2 1 2 2 1

```
* `%@#&>+` And add the reciprocals of each line length elementwise:

```
2.083 2.083 1.0303 2.071 2.071 1.1429

```
* `{.@\:` Use that result to sort the input descending, and take the first:

```
┌────────────┐
│Hello, world│
└────────────┘

```

# Answer
> 5 votes
# JavaScript (Node.js), ~~65~~ 61 bytes

```
x=>x.sort(g=(a,b)=>a?(x.map(b=>b!=a?x:0)+a).length-g(b):0)[0]

```

Try it online!

Sort `<different lines>*(<input length>-1)+<element length>`

# Answer
> 5 votes
# PARI/GP, 38 bytes

```
s->vecsort(s,a->[[1|l<-s,a!=l],#a])[1]

```

Attempt This Online!

Based on @l4m2's JavaScript answer.

Takes a list of lines.

---

# PARI/GP, 46 bytes

```
s->vecsort(matreduce(s)~,a->#a[1]*I-a[2])[1,1]

```

Attempt This Online!

Takes a list of lines.

# Answer
> 5 votes
# Jelly, 6 bytes

```
Æṃ'LÞḢ

```

Try it online!

For some reason, Jelly's mode atom insists on vectorising over a list of lines, so we need `'`

# Answer
> 4 votes
# Japt `-g`, 9 bytes

Input as an array of lines.

```
ü üÊÌcÌñÊ

```

Try it

```
ü üÊÌcÌñÊ     :Implicit input of array
ü             :Group & sort by value
  ü           :Group & sort by
   Ê          :  Length
    Ì         :Last element
     c        :Flat map
      Ì       :  Last element
       ñ      :Sort by
        Ê     :  Length
              :Implicit output of first element

```

# Answer
> 3 votes
# Vyxal, ~~11~~ 7 bytes

```
vOÞMİÞg

```

Try it Online!

## Explained

```
vOÞMİÞg
vO       # [input.count(item) for item in input]
  ÞM     # indices of maximal items
    İ    # indexed into the input
     Þg  # shortest by length

```

# Answer
> 3 votes
# Retina 0.8.2, 40 bytes

```
O`
O^$#`
$.&
O^$#`(.+¶)(?=(\1)*)
$#2
1G`

```

Try it online! Takes input as a list of newline-terminated strings. Explanation:

```
O`

```

Sort everything.

```
O^$#`
$.&

```

Sort order of length, then reverse the result. The reverse in the next sort will then bring the shortest line of equal occurrence count back to the front.

```
O^$#`(.+¶)(?=(\1)*)
$#2

```

Sort by count of subsequent occurrences. Only one of each of the most frequent lines will actually sort last, but that doesn't matter because we only need one of them. The sort is stable, so the most frequent lines remain sorted in descending order of length. The result is then reversed, bringing the shortest most frequent line to the start.

```
1G`

```

Keep only the first line.

# Answer
> 2 votes
# Factor,  ~~62 61~~  60 bytes

```
[ [ length ] sort-with dup histogram '[ _ at ] supremum-by ]

```

Try it online!

* `[ length ] sort-with` Sort by ascending length.
* `dup histogram '[ _ at ] supremum-by` Find the most frequent element that is encountered first.

# Answer
> 2 votes
# Scala 3, 40 bytes

```
s=>s.maxBy(l=>(s.count(Set(l)),-l.size))

```

Returns a tuple from the comparison key, which are ordered lexicographically.

Attempt This Online!

# Answer
> 2 votes
# PowerShell, 49 bytes

```
($input|group|sort C*,{-$_.Name.Length})[-1].Name

```

Try it online!

Input comes from the pipeline.

`$input` is an automatic variable that enumerates all input that is piped to a function.
The lines are passed to the cmdlet `Group-Object` which groups identical lines into GroupInfo objects with the properties Count and Name (the original line).
The objects are then `sort`ed first by the Count property (how often a line was found), and then the negative (so both Count and Length can be sorted ascending) length of the line.
Then the last element of the sorted array `[-1]` is taken, and its Name property returned.
Output is implicit.

Will return "Woah, love me do" (same length as "Love, love me do") for the Beatles because of the ascending sorting.

# Answer
> 2 votes
# Go, 140 bytes

```
import."strings"
func f(s string)(O string){m,M:=-1,make(map[string]int)
for _,l:=range Split(s,"\n"){if M[l]+=1;M[l]>m{O,m=l,M[l]}}
return}

```

Attempt This Online!

# Answer
> 2 votes
# Charcoal, 23 bytes

```
ＷＳ⊞υι≔Ｅυ⟦№υι±Ｌι⟧θ§υ⌕θ⌈θ

```

Try it online! Link is to verbose version of code. Takes input as a list of newline-terminated strings. Explanation: Port of @mousetail's original Python answer.

```
ＷＳ⊞υι

```

Input the lines of the song.

```
≔Ｅυ⟦№υι±Ｌι⟧θ

```

Get the count and negated length of each line.

```
§υ⌕θ⌈θ

```

Output the line that has the maximum value of that.

# Answer
> 1 votes
# Pip `-r`, 15 bytes

```
@Y-(_Ng)AE#_SKg

```

The `-r` flag reads the program arguments from lines of stdin rather than command-line args. Attempt This Online!

### Explanation

```
@Y-(_Ng)AE#_SKg
              g  ; Lines of stdin (due to -r flag)
            SK   ; Sort ascending according to this key function:
    _Ng          ;   Number of occurrences of this line in the input list
  -(   )         ;   Negated
        AE       ;   Placed in a list with
          #_     ;   Length of the line
 Y               ; No-op, necessary for parsing
@                ; Get the first element of the sorted list

```

# Answer
> 1 votes
# Arturo, 41 bytes

```
$[a][minimum arrange a=>size=>[size--a&]]

```

Try it

```
$[a][                     ; a function taking an argument a
    minimum               ; get minimum element of
    arrange a=>size       ; input sorted by ascending length
    =>[                   ; by
        size              ; length of
        --                ; set difference between
        a                 ; input
        &                 ; current line
    ]                     ; end minimum
]                         ; end function

```

# Answer
> 0 votes
# Nekomata, 4 bytes

```
ŢṂaş

```

Attempt This Online!

```
ŢṂ      Maximum by count
  aş    Minimum by length

```

# Answer
> 0 votes
# Mathematica, 59 bytes

Try it online!

```
f@a_:=Commonest[Select[a,Length[#]==Max[Length/@a]&]][[1]];

```

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


# Question
Title: Shortest code to determine if a string is a palindrome
A *palindrome* is some string that is spelled the same way both backwards and forwards. For instance, 'Eva, can I stab bats in a cave?' is a palindrome (EVACANISTAB | BATSINACAVE)

For this code golf, using the language of your choice, determine if a given string is a palindrome or not.

*Edge Cases:*

* Punctuation is not counted towards palindrominess.
* Control characters are not counted towards palindrominess.
* Whitespace is not counted towards palindrominess.
* Numbers are counted towards palindrominess.
* Case in this challenge is not counted towards palindrominess.
* There is no limit to the length of strings to evaluate, except for what is imposed by your language of choice.
* For this challenge, limit yourself to the ASCII character set.

*Technical Requirements:*

* Only method bodies are needed; additional things like method signatures, data structure declarations, etc. do not count towards the victory requirement.
* Code must compile or interpret without compile-time errors or exceptions.
* Code must not throw any unhandled exceptions or crash. (Almost needless to say. Almost.)
* Code must return some value indicating palindrominess. The data type depends on the language you use (e.g. a C# user might use a `bool`, whereas a JavaScript user could use a `var`.)
* You may not write your own interpreter that performs this task as a 'native' capability so you can 'golf' a near-winning score. (Hopefully needless to say.)

*Victory Condition:*

* The shortest code in characters wins.

# *Current Leader: tmartin (k, 25 characters)*

...Want the magic green check mark by *your* answer? Beat this guy's answer!

# Answer
## K, 25

```
{x~|x:_x@&x in,/.Q`a`A`n}

```

.

```
k){x~|x:_x@&x in,/.Q`a`A`n}"Eva, can I stab bats in a cave?"
1b

```
> 30 votes

# Answer
## Perl, 26 char

```
s/_|\W//g;uc eq reverse uc

```

Evaluates to 1 when `$_` is a palindrome, `""` (one of Perl's false values) when it is not.

Sample usage:

```
sub palin {
    s/_|\W//g;uc eq reverse uc
}
while (<DATA>) {
    chomp;
    print "$_ => ",palin()?"yes":"no","\n";
}
__DATA__
Eva, can I stab bats in a cave?
A man, a plan, a canal. Panama!
Madam, I'm Adam Carolla.
757
Boeing 757
A man, a plan, a big shovel, a canal. Panama!
A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats, a peon, a canal >> __Panama__

```

output:

```
Eva, can I stab bats in a cave? => yes
A man, a plan, a canal. Panama! => yes
Madam, I'm Adam Carolla. => no
757 => yes
Boeing 757 => no
A man, a plan, a big shovel, a canal. Panama! => no
A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats, a peon, a canal >> __Panama__ => yes

```
> 25 votes

# Answer
### C# 82 only :)

```
var x=s.ToLower().Where(char.IsLetterOrDigit);return x.SequenceEqual(x.Reverse());

```

Couldn't resist the temptation of writing a boilerplate-free program in my favorite language.

A test is available here: http://ideone.com/8bwz7z
> 17 votes

# Answer
### GolfScript, ~~36 34 31~~ 30 characters

```
{0"0:A[a{"@{>^}+/},{32|}%.-1%=

```

Similar algorithm to my previous (Javascript) solution.

`0"0:A[a{"@{>^}+/` -- Optimised by Peter Taylor and Howard. My version was `"/9@Z"{1$<},,2%\;`. Howard donated function concatenation and Peter Taylor donated XOR for modulo-2. It's basically a generic method of comparing if the value is in a sequence of ranges.

`{.96>32*-}%` (11 characters) is not really an improvement over Javascript's `.toUpperCase()` (14 characters), especially since it mangles some weird punctuation that follows `z` in the ASCII table (which doesn't matter here).

as Peter Taylor's suggested, however, if we filter out alphanumerics first, we can convert to lowercase and digits just by setting one bit in each character: `{32|}`

`.-1%=` does all the palindromic heavy lifting. One part I'm not really fond of is how long it took me to find out how to reverse an array. I should have read the docs. The other two characters perform stack management and comparison.

Test: http://golfscript.apphb.com/?c=IkV2YSwgY2FuIEkgc3RhYiBiYXRzIGluIGEgY2F2ZT8iCgp7IjA6QVtheyJcez59KywsMiV9LHszMnx9JS4tMSU9

---

Further, if I can assume that none of the following control characters are present: (Data link escape, device control 1-4, negative acknowledge, synchronous idle, end of transmission block, cancel, end of medium) (we all agree these are all pretty obscure) or if I can treat them as uppercase versions of the digits 0-9, we can save another two characters:

## GolfScript, 28 characters

```
{32|}%{0"0:a{"@{>^}+/},.-1%=

```

Test: http://golfscript.apphb.com/?c=IkV2YSwgY2FuIEkgc3RhYiBiYXRzIGluIGEgY2F2ZT8iCgp7MzJ8fSV7MCIwOmF7IkB7Pl59Ky99LC4tMSU9
> 13 votes

# Answer
### Javascript, 53 characters:

```
(x=x.toLowerCase().match(/[a-z\d]/g))+""==x.reverse()

```

is a javascript expression that evaluates to true if `x` is a palindrome, to false if it isn't. It assumes `x` is a string. If that's not guaranteed, prepend `x+="",`

Here's a breadcrumb: Due to how `reverse()` works,

```
(x=x.toLowerCase().match(/[a-z\d]/g))==""+x.reverse()

```

fails. However,

```
""+(x=x.toLowerCase().match(/[a-z\d]/g))==x.reverse()

```

is perfectly fine.
> 8 votes

# Answer
**Python 2: 49** (without counting the method signature)

```
def f(s):
 s=filter(str.isalnum,s.upper())
 return s==s[::-1]

```

A complete program, with input and output can be writte in **74** characters.

```
import sys
s=filter(str.isalnum,sys.stdin.read().upper())
print s==s[::-1]

```

Example usage:

```
$echo 'Eva,can I stab bats in a cave?' | python palindrome.py
True
$ cat huge_palindrome.txt | python palindrome.py
True
$echo 'Able was I ere i SaW elBa' | python palindrome.py
True

```

(`huge_palindrome.txt` contains this 17,826 word palindrome)

This solution can be adapted to python 3 adding some characters:

**Python 3: 55**

```
def f(s):
 s=list(filter(str.isalnum,s.upper()))
 return s==s[::-1]

```
> 8 votes

# Answer
# Bash: ~~52~~ ~~48~~ 46 characters

```
s=${1,,};s=${s//[^a-z0-9]};[ $s = `rev<<<$s` ]

```

This takes the sting to check as first parameter and sets the exit code to 0 for palindrome and 1 for not.

Sample run:

```
bash-4.2$ p() { s=${1,,};s=${s//[^a-z0-9]};[ $s = `rev<<<$s` ]; }

bash-4.2$ p 'Eva, can I stab bats in a cave?'; echo $?
0

bash-4.2$ p 'A man, a plan, a canal. Panama!'; echo $?
0

bash-4.2$ p "Madam, I'm Adam Corolla."; echo $?
1

bash-4.2$ p '757'; echo $?
0

bash-4.2$ p 'Boeing 757'; echo $?
1

bash-4.2$ p 'A man, a plan, a shovel, a canal. Panama!'; echo $?
1

bash-4.2$ p 'A_man,_a_plan, a_caremer, a canal:_Panama!'; echo $?
0

```
> 8 votes

# Answer
# Mathematica ~~54~~ 53

One byte saved thanks to CatsAreFluffy:

```
PalindromeQ@StringCases[ToUpperCase@#,WordCharacter]&

```

For those with version 10.2 or earlier:

```
#==Reverse@#&@StringCases[ToUpperCase@#,WordCharacter]&

```

**Example**

```
PalindromeQ@StringCases[ToUpperCase@#, WordCharacter]&["Eva,can I stab bats in a cave?"]

```

> True
> 7 votes

# Answer
**JAVA (or the most verbose language ever), ~~102~~ ~~96~~ 95 char**

```
s=s.replaceAll("\\W|_","");return s.equalsIgnoreCase(new StringBuffer(s).reverse().toString());

```

Usage (with ungolfed code):

```
static boolean q(String s) {
    s=s.replaceAll("\\W|_","");
    return s.equalsIgnoreCase(new StringBuffer(s).reverse().toString());
}

public static void main(String[] args) {
    System.out.println(q("'A man, a plan, a canal - Panama!'"));
}

```

Shortened with the help of the commenter below
> 7 votes

# Answer
## R: 66

```
w=grep("[a-z0-9]",strsplit(tolower(s),"")[[1]],v=T);all(w==rev(w))

```

Usage:

```
f=function(s){w=grep("[a-z0-9]",strsplit(tolower(s),"")[[1]],v=T);all(w==rev(w))}

f("Eva, can I stab bats in a cave?")
[1] TRUE

```
> 7 votes

# Answer
# k (~~50 48 45~~ 38 chars)

Suppresses all errors, returning a default of `0b` (false).

```
{X~|X@:&(X:_:x)in 10h$(48+!10),97+!26}

```

Example:

```
k){X~|X@:&(X:_:x)in 10h$(48+!10),97+!26} "Eva, can I stab bats in a cave?"
1b

```

edit: shaved three more character by avoiding intermediate variable. H/T, CS. -7: No need to suppress errors.
> 6 votes

# Answer
## J, 30 characters

```
*/(=|.)tolower(#~'[^_\W]'rxE])

```

Usage:

```
   */(=|.)tolower(#~'[^_\W]'rxE])'A man, a plan, a canal - Panama!'
1
   */(=|.)tolower(#~'[^_\W]'rxE])'Doc, note: I dissent. A fast never prevents a fatness. I diet on cod'
1

```
> 6 votes

# Answer
# Ruby: ~~43~~ 38 characters

```
s=s.upcase.tr'^A-Z0-9','';s==s.reverse

```

Sample run:

```
irb(main):001:0> p=->s{s=s.upcase.tr'^A-Z0-9','';s==s.reverse}
=> #<Proc:0x854592c@(irb):1 (lambda)>

irb(main):002:0> p['Eva, can I stab bats in a cave?']
=> true

irb(main):003:0> p['A man, a plan, a canal. Panama!']
=> true

irb(main):004:0> p["Madam, I'm Adam Corolla."]
=> false

irb(main):005:0> p['757']
=> true

irb(main):006:0> p['Boeing 757']
=> false

irb(main):007:0> p['A man, a plan, a shovel, a canal. Panama!']
=> false

irb(main):009:0> p['A_man,_a_plan, a_caremer, a canal:_Panama!']
=> true

```
> 5 votes

# Answer
# C++, ~~107~~ (miscounted), ~~100~~ (miscounted), 81

```
string s;for(int c:t)if(isalnum(c))s+=c|32;return s==string(s.rbegin(),s.rend());

```
* Exploits ASCII bit patterns.
* Relies on an evil `using namespace std;`.
* Uses bitwise AND and OR instead of the logical operators.
* Uses `int` because it's shorter than `char` or `auto`.

```
#include <string>
using namespace std;

bool IsPalindrome(const string & t) {
string s;for(int c:t)if(isalnum(c))s+=c|32;return s==string(s.rbegin(),s.rend());
}

#include <cassert>

int main() {
    assert(!IsPalindrome("gorilla"));  // simple failure
    assert( IsPalindrome("racecar"));  // simple success
    assert( IsPalindrome("Hannah"));   // case blind
    assert(!IsPalindrome("1999"));     // digit failure
    assert( IsPalindrome("2002"));     // digit success
    // Ignore spacing, punctuation, and case:
    assert( IsPalindrome(" \t09AZ/:@[`{za90"));  // boundaries
    assert( IsPalindrome("A man, a plan, a canal: Panama."));
    assert( IsPalindrome("Eva, can I stab bats in a cave?"));
    assert( IsPalindrome(""));  // empty string
    return 0;
}

```
> 5 votes

# Answer
# Lua, 56

```
a=io.read"*l":lower():gsub("%W","")print(a:reverse()==a)

```
> 4 votes

# Answer
**Python 3/2 59 chars:**

```
def pld(i):
   p=[c for c in i.lower() if c.isalnum()]
   return(p == p[::-1])

```
> 4 votes

# Answer
# Haskell, 43

Using the standard libraries `Control.Monad`, `Control.Monad.Instances`, and `Data.Char`:

```
ap(==)reverse.map toLower.filter isAlphaNum

```
> 4 votes

# Answer
**PHP 60 characters.**

First try on codegolf.

```
//thank you manatwork
echo($x=preg_replace('/\W/','',strtolower($c)))==strrev($x);

```

Example:

```
$c='Eva, can I stab bats in a cave?';
echo($x=preg_replace('/\W/','',strtolower($c)))==strrev($x);
//prints 1

```
> 4 votes

# Answer
**Python 2 64 Charecters:**

```
i =''.join(re.findall('[a-z0-9]+',i.lower()))
return i==i[::-1]

```
> 3 votes

# Answer
# Haskell 48

```
(\x->x==reverse x).map toLower.filter isAlphaNum

```

used like this:

```
(\x->x==reverse x).map toLower.filter isAlphaNum$"Eva, can I stab bats in a cave?"

```
> 3 votes

# Answer
**Smalltalk**, Squeak/Pharo flavour
**116** chars using traditional formatting with tabs

You add two methods to String:

```
selffles
    ^self = self reverse
isPalindrome
    ^(self asUppercase asDecomposedUnicode select: #isAlphaNumeric) selffles

```

We could of course eliminate some spaces, or use shorter method names, but let's not betray the spirit of Smalltalk.

More over, this will handle French palindromes, like in http://fr.wikipedia.org/wiki/Liste\_de\_palindromes\_fran%C3%A7ais, not many answers in this page can.

```
['Léon a trop par rapport à Noël' isPalindrome] assert.

```
> 3 votes

# Answer
# Python 3 (51 char)

### and may be Python 2

based on *abhiram* solution (with more agressive golfing)

```
from re import findall

def palindrome(i):
 i=findall('[a-z\d]',i.lower())
 return i==i[::-1]

print(palindrome(input('Phrase: ')))

```

may be shortened to 46 chars, using RE '\w'

and variant with extremely shortened function body (27 chars)

```
import re
l=str.lower
f=re.compile('[a-z\d]').findall

def palindrome(i):i=f(l(i));return i==i[::-1]

print(palindrome(input('Phrase: ')))

```
> 3 votes

# Answer
# Julia 1.0, 63 bytes

```
~s=((x=filter(in(['0':'9';'A':'Z']),uppercase(s)))==reverse(x))

```

Try it online!

Since punctuation is filtered out, `"5,000 0.005"` is considered a palindrome.
> 3 votes

# Answer
## Windows PowerShell, 56 47 45 chars

Updated (see comments), and can remove the brackets around the regex:

```
($s=$s-replace'\W')-eq(-join$s[$s.length..0])

```

Original (56)

```
$s=$s-replace'[^\w]','';$s-eq($s[-1..-$s.length]-join'')

```

Original Un-golfed:

```
$s = "Eva, can I stab bats in a cave?"
$s = $s -replace '[^\w]', ''
$rev = $s[-1..-$s.length] -join ''
$s -eq $rev

```
> 2 votes

# Answer
# C++, 74 bytes

This code is actually really elegant, and easy to understand (when formatted correctly). I don't believe it's possible to get any shorter in C++, and it doesn't use any standard library functions.

```
p(auto c){auto e=c;while(*e)++e;--e;while(*e==*c&e>c)--e,++c;return e<=c;}

```

Example usage:

```
p("Hello"); //Outputs 0
p(""); //Outputs 1
p("a"); //Outputs 1
p("HellolleH"); //Outputs 1

```

Nicely formatted version:

```
p(auto c)
{
    auto e=c;
    while(*e) ++e;
    --e;
    while(*e==*c & e>c)--e,++c;
    return e<=c;
}

```
> 2 votes

# Answer
# PHP, ~~26 84 80 78 62~~ 63 bytes

```
<?=strrev($s=strtolower(preg_replace("#\W#","",$argv[1])))==$s;

```

takes input from first command line argument; prints `1` for truthy, empty string for falsy.

---

I18n is a littly expansive, as there is no multibyte alternative for `strrev` (110 bytes; run with `-r`):

```
preg_match_all("#.#us",$s=strtolower(preg_replace("#\W#u","",$argv[1])),$m);echo$s==join(array_reverse($m[0]);

```

utf8\_strrev blatantly stolen from the PHP manual. You might also want to take a look at this blog post.
> 2 votes

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

```
#|:\(2!"0:a{"')__:

```

Try it online!

Uses @scrawl's suggestion here to return `1` for palindromes and `2` for non-palindromes. If `1` and `0` are required, the solution can be adjusted by prefixing `1=`.

* `_:` lowercase the (implicit) input
* `(...)_` filter out values where the code in `(...)` returns a non-0 value
    + `2!"0:a{"'` do a bins lookup, then mod the result by two; returns `0` if the input is within `"a"-"z"` or `"0"-"9"` and `1` otherwise
* `|:\` set up a converge-scan, reversing the input until the original input is returned. on palindromes, returns a one-item list; on non-palindromes, a two-item list
* `#` take the count of the result from above. As noted, if a strict `1` and `0` output are required for palindrome/non-palindrome, prefix `1=` for two bytes
> 2 votes

# Answer
## Ruby, 48

```
p((g=gets.upcase.gsub /[^A-Z\d]/,'')==g.reverse)

```

Quite simple, and hastily made so not golfed too much. I shall golf it more later.
> 1 votes

# Answer
# Pylongolf2, 24 bytes

```
c╨2"[^a-zA-Z]"-_╨1=~

```

`c` takes the input, `╨2` to convert to lower case.
I then push a regex onto the stack and use `-` to remove all non-alphabetical characters in the input.
`_` duplicates the input.
`╨1` reverses it and `=` then compares them.
`~` prints the stack in the end which prints either `true` or `false`.
> 1 votes

# Answer
# PowerShell, ~~194~~ 190 bytes

A recursive implementation to show how an unnamed PowerShell scriptblock can call itself.

```
$P={param([string]$s)$s=($s-replace'[^a-z]').tolower();if(!$s){return $true};if($s.length-lt4){return $s[0]-eq$s[-1]};$s[0]-eq$s[-1]-and(&$MyInvocation.MyCommand.ScriptBlock $s.trim($s[0]))}

```

ungolfed:

```
$P={
param([string]$s)
$s=($s-replace'[^a-z]').tolower();
if(!$s){return $true};
if($s.length-lt4){return $s[0]-eq$s[-1]};
$s[0]-eq$s[-1]-and(&$MyInvocation.MyCommand.ScriptBlock $s.trim($s[0]))
}

```

tests:

```
&$P "Eva, can I stab bats in a cave?"
&$P "Eva, can I stab cats in a cave?"
&$P "A man, a plan, a canal. Panama!"
&$P "A man, a plan, a big shovel, a canal. Panama!"
&$P "Madam, I'm Adam."
&$P "Madam, I'm Adam Corolla."
&$P "757"
&$P "Boeing 757"

```
> 1 votes

# Answer
# 05AB1E, 4 bytes

```
álÂQ

```

Explanation:

```
á     # Only keep the alphabetic characters.
 l    # Lowercase the characters.
  Â   # Bifurcate, which duplicates the letters and reverses the duplicate.
   Q  # Check if they are equal.

```

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

# Answer
# Jelly, 10 Characters

```
fØBŒl
UÇ⁼Ç

```

Returns 1 if true, 0 if false

Try it Online!
> 1 votes

# Answer
# Racket, 132 bytes

Pretty embarrassing, but maybe somebody can see a way of making this shorter!

```
((λ(l[n(floor(/(length l)2))])(equal?(take l n)(take(reverse l)n)))(string->list(regexp-replace*"[^0-9a-z]"(string-downcase s)"")))

```

### Code listing with test module

```
#lang racket

(define/contract (palindrome? s)
  (string? . -> . boolean?)
  ((λ(l[n(floor(/(length l)2))])(equal?(take l n)(take(reverse l)n)))(string->list(regexp-replace*"[^0-9a-z]"(string-downcase s)""))))

(module+ test
  (require rackunit)
  (define tests
    '(("Eva, can I stab bats in a cave?" . #t)
      ("A man, a plan, a canal. Panama!" . #t)
      ("Madam, I'm Adam Corolla." . #f)
      ("757" . #t)
      ("Boeing 757" . #f)
      ("A man, a plan, a big shovel, a canal. Panama!" . #f)
      ("A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats, a peon, a canal >> __Panama__" . #t)))
  (for ([t tests])
    (check-equal? (palindrome? (car t)) (cdr t) (~a t))))

```
> 1 votes

# Answer
# APL, ~~78~~ 65 Bytes

```
l←⎕D,⎕UCS v+32⊣c←⎕D,⎕UCS v←64+⍳26⋄(⌽≡⊢)∊{⍵/⍨⍵∊l}¨{⍵∊c:l[c⍳⍵]⋄⍵}¨⎕

```

I'm going to assume that the Original Poster meant limit the INPUT string to the Ascii character set.
> 1 votes

# Answer
# C++14, 104 bytes

Actually overlooked the requirement to ignore case and whitespace, so here is:

```
auto f=
[](auto s,int&n){
auto r=s.rbegin();n=1;for(auto c:s){if(isalnum(c)){while(!isalnum(*r))r++;if((c|32)!=(*(r++)|32))n=0;}}
}
;

```

# strict solution, ~~72~~ 68 bytes

-4 bytes for returning by parameter.

As unnamed lambda, assuming input `s` is of type `std::string` and returning the result by a parameter:

```
[](auto s,int&n){auto r=s.rbegin();n=1;for(auto c:s)if(c!=*r++)n=0;}

```

Ungolfed & usage:

```
#include <iostream>
#include <string>

auto f=
[](auto s, int& n){
  auto r=s.rbegin();
  n=1;
  for(auto c:s)
    if(c!=*r++)
      n=0;
}
;

int main(){
int n;
#define p(s) f(std::string(s),n); std::cout << n << std::endl
 p("Hello");
 p("ABCCBA");
 p("ABCBA");
}

```
> 1 votes

# Answer
# Python 2.7.6, 79 bytes

"Sorry I don't get what characters to count so I wrote the whole program"

```
import re
n=raw_input()
n=re.sub("[^a-z]+","",n.lower())
print n==n[::-1]

```

> This will print **True** if input string is palindrome else **False**.

Code\_link: http://ideone.com/b4NzLD
> 1 votes

# Answer
## REXX, 84 bytes

```
arg n
n=space(translate(n,,translate(n,,xrange(a,z)xrange(0,9))),0)
say n=reverse(n)

```

`arg n` reads argument into variable `n`, converting it to upper-case.

`xrange(a,z)xrange(0,9)` concatenates the two ranges A—Z and 0—9.

`translate` takes a string to process, an output translation table and an input translation table, and optionally a padding character to replace those characters not found in the output table with. Hence `translate(n,,xrange(a,z)xrange(0,9))` maps the string `n` with an input table consisting only of alphanumerical characters and an empty output table, resulting in a string consisting only of punctuation, spaces and other non-alphanumericals (since they were not in either table). The filtered-out characters are rendered as spaces.

`translate(n,,translate(n,,xrange(a,z)xrange(0,9)))` uses the above non-alphanumerics string as an input table and an empty output table, applying it to `n`, resulting in a string consisting only of alphanumericals, since they were not in the input or output tables. The non-alphanumerics are rendered as spaces.

`space()` takes a string and a number, spacing out the words with the supplied amount of spaces between. In this case, the supplied number is `0`, hence all spaces are removed.

By this point, `n` has been reduced to consisting only of alphanumeric characters without any spaces.

`say n=reverse(n)` prints out whether `n` is identical to its reversed version.
> 1 votes

# Answer
# Dyalog APL (18 characters)

```
 {⍵≡⌽⍵}'\w'⎕S'\u0'⊢

```

Search for alphanumeric characters in the right argument, and return any found upper-cased (this avoids any need for punctuation, whitespace and casing). Then just check what's returned to see if it matches the reverse.

## Example

```
{⍵≡⌽⍵}'\w'⎕S'\u0'⊢'Eva, can I stab bats in a cave?'
    1

```
> 1 votes

# Answer
# Vyxal, 6 bytes

```
kr↔⇩Ḃ=  #

```

```
kr      # push the upper and lowercase alphabet
  ↔⇩    # remove all chars in input that are not in that, and lowercase
    Ḃ   # push a and a.reverse()
     =  # equal?

```

Try it Online!
> 1 votes

# Answer
# Thunno 2, 4 bytes

```
LỊḲ⁼

```

Try it online!

#### Explanation

```
LỊḲ⁼  # Implicit input
L     # Convert to lowercase
 Ị    # Only keep alphabetic characters
  Ḳ   # Duplicate and reverse
   ⁼  # Are they equal?
      # Implicit output

```
> 1 votes

# Answer
# Swift, 82 77 bytes

```
let t=s.lowercased().replacing(/[\W_]/,with:"");return Array(t)==t.reversed()

```

Where `s` is a `String` argument. I think it's rather self-explanatory — that's the beauty of Swift.
> 1 votes

# Answer
JavaScript Code :: ONLY 140 characters Palindrome

```
function palindrome()
{
    var user=prompt("Enter the characters to check the palindrome");
    var split=user.split('').reverse().join(''); // ONLY this line counts
    if(user == split)
    {
        alert("The given word is a Palindrome");
    } else
    {
        alert("The given word is not a Palindrome");
    }

}

```

palindrome();
> 0 votes

# Answer
## Racket 118 bytes

```
(let((l(filter(λ(x)(or(char-alphabetic? x)(char-numeric? x)))(string->list(string-upcase s)))))(equal? l(reverse l)))

```

Ungolfed:

```
(define (palindrome? s)
  (let((l(filter(λ(x)(or(char-alphabetic? x)
                        (char-numeric? x)))
                (string->list (string-upcase s)))))
    (equal? l(reverse l))))

```

Testing:

```
(palindrome? "abc  dcB;_A")
(palindrome? "abc;@#$zdc b  a")
(palindrome? "1%^&234 56")
(palindrome? "1a234 * ^ && 565432A1")

```

Output:

```
#t
#f
#f
#t

```
> 0 votes

# Answer
# AHK, 83 bytes <sup><sup><sup><sup>(L7 loser)</sup></sup></sup></sup>

```
StringUpper,s,1
s:=RegExReplace(s,"[\W_]")
Loop,Parse,s
t:=A_LoopField t
Send % s=t

```

Outputs `1` for palindromes and `0` for not.
> 0 votes

# Answer
**C, 199 bytes**

```
#define R return
#define C unsigned char
#define F for
s(C*a){C*b;if(a&&*a)F(b=a+strlen(a)-1;;++a,--b){F(;a<b&&!isalnum(*a);)++a;F(;a<b&&!isalnum(*b);)--b;if(a>=b)R 1;if((*a|32)-(*b|32))R 0;}R 1;}

```

//ungolf

```
v(C*a)
{ C*b;
 if(a&&*a)
   F(b=a+strlen(a)-1;;++a,--b)
           {F(;a<b&&!isalnum(*a);)++a;
            F(;a<b&&!isalnum(*b);)--b;
            if(a>=b)           R 1;
            if((*a|32)-(*b|32))R 0;
           }
 R 1;
}

#define P printf
main()
{C*b="Eva, can I stab bats in a cave?";
 P("%s %d\n", b, s(b));
 R 0;
}

```

//results

```
//Eva, can I stab bats in a cave? 1

```
> 0 votes

# Answer
# Common Lisp, ~~72~~ 65 bytes

```
(let((y(remove-if-not'alphanumericp(read))))(equalp(reverse y)y))

```

*-7 bytes thanks to @ceilingcat !*

Try it online!
> 0 votes

# Answer
# Retina, 31 bytes

```
\W

T`l`L
+`^(.)(.*)\1$
$2
^.?$

```

Try it online!
> 0 votes

# Answer
# QuadS, 19 bytes

Equivalent to James Heslip's solution.

```
⍵≡⌽⍵
\w
\u&

```

Try it online!

*Is…*

`⍵≡⌽⍵` the text identical to its reverse

`\w` after finding all word characters

`\u&` and uppercasing them

*?*
> 0 votes

# Answer
# C (gcc), 118 bytes

```
p(s,n)char*s,*n;{char*r=s+strlen(s)-1;for(*n=1;*s;s++)if(isalnum(*s)){for(;!isalnum(*r);r--);*n*=(*s|32)==(*r--|32);}}

```

Try it online!

Used like: `p(string, &result);`; outputs by modifying `result`.
> 0 votes

# Answer
# Japt v2.0a0, 8 bytes

```
k\W v
¶Ô

```

Try it

```
k\W v\n¶Ô     :Implicit input of string U
k             :Remove
 \W           :  RegEx /[^a-z0-9/gi
    v         :Lowercase
     \n       :Reassign to U
       ¶      :Is equal to
        Ô     :Reverse

```
> 0 votes

# Answer
```
n=>n.split('').reverse().join('')==n;

```
> 0 votes

# Answer
# Zsh, 42 bytes

```
s=${(L)1//[^A-Za-z0-9]}
<<<${s/`rev<<<$s`}

```

Try it online!

Truthy (palindrome) is empty string, falsy otherwise. TIO link includes a test harness that outputs `T` or `F`.
> 0 votes

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