title: Don't google "google"

text:
# Question
Title: Don't google "google"
We all know that if you google the word "google" it will break the internet.

Your task is to create a function that accepts one string and returns its length, in the fewest possible Unicode characters.

However, if the given string is `google` (lowercase), it will cause an error.

For example, `g('bing')` will return `4` but `g('google')` will cause an error.

Please provide an example of usage, and the error if possible.

# Answer
> 243 votes
## Python 2, 29

```
lambda x:len(x)/(x!='google')

```

Gives a `ZeroDivisionError` on `"google"`, and the length otherwise. This takes advantage of Python's booleans equaling `0` and `1`.

# Answer
> 116 votes
# Excel, 23 characters

Paste this into a cell other than A1 and type your search query into A1.

```
=LEN(A1)/(A1<>"google")

```

For example:

# Answer
> 84 votes
# C#, 43 bytes

An improvement over Salah Alami's answer. Recurses to throw a stack overflow exception on providing "google"

```
int g(string s)=>s!="google"?s.Length:g(s);

```

# Answer
> 57 votes
# Pyth, ~~14~~ 13 characters

```
L/lbnb"google

```

Defines a named function `y`.

This divides the length by 1 if the string is not *google* and by 0 otherwise. The idea is not novel, but I came up with it independently.

Try it online.

### How it works

```
L                 Define y(b):
  lb                Compute len(b).
    nb"google       Compute (b != "google").
 /                  Set _ = len(b) / (b != "google").
                  Return _. (implicit)

```

# Answer
> 45 votes
# MATLAB, ~~63~~ ~~41~~ ~~40~~ ~~38~~ 36 bytes

## Thanks to Tom Carpenter for shaving off 1 byte!

## Thanks to Stewie Griffin for shaving off 2 bytes!

```
@(x)nnz(x(+~strcmp('google',x):end))

```

Unlike the other more elegant solutions, performing a division by zero operation in MATLAB will not give an error, but rather `Inf`. This solution finds the length of the string by `nnz`. The string that is produced is in such a way that you index from the beginning of the string to the end, which is essentially a copy of the string. However, what is important is that the beginning of where to access the string is produced by checking whether or not the input is equal to `'google'`. If it isn't, this produces a beginning index of 1 and we index into the string normally... as MATLAB starts indexing at 1. Should it be equal, the index produced is 0 and MATLAB will throw an indexing error stating that the index needs to be a positive integer. The extra `+` is to ensure that the output of the equality check is numerical rather than Boolean/`logical`. Omitting the `+` will produce a warning, but because this challenge's specifications doesn't allow for warnings, the `+` is required... thus completing the code.

# Example uses

```
>> f=@(x)nnz(x(+~strcmp('google',x):end)) %// Declare anonymous function

f =

    @(x)nnz(x(+~strcmp('google',x):end))

>> f('bing')

ans =

     4

>> f('google')
Subscript indices must either be real positive integers or logicals.

Error in @(x)nnz(x(+~strcmp('google',x):end))

```

---

# A more fun version, ~~83~~ ~~77~~ ~~76~~ ~~74~~ 72 bytes

## Thanks to Tom Carpenter for shaving off 1 byte!

## Thanks to Stewie Griffin for shaving off 2 bytes!

```
@(x)eval('if strcmp(''google'',x),web([x ''.com/i'']);else nnz(x),end');

```

The above isn't an official submission, but it's something that's a bit more fun to run. Abusing `eval` within anonymous functions, what the code does is that it checks to see if the input string is equal to `'google'`... and if it is, this will open up MATLAB's built-in web browser and shows Google's 404 error page trying to access the subpage located at `i` when that doesn't exist. If not, we display the length of the string normally.

# Example uses

```
>> f=@(x)eval('if strcmp(''google'',x),web([x ''.com/i'']);else nnz(x),end'); %// Declare anonymous function
>> f('bing')

ans =

     4

>> f('google')
>>

```

The last call using `'google'` gives us this screen:

# Answer
> 32 votes
# JavaScript ES6, ~~34~~ ~~27~~ 25 characters

```
f=>f=='google'?Δ:f.length

```

Throws a ReferenceError on `Δ` for google.

```
alert((f=>f=='google'?Δ:f.length)('test'))
```

# Answer
> 29 votes
# TI-BASIC, 15 bytes

Heck, while we're at it, might as well get a TI-BASIC answer in here.

Input format is `"string":prgmNAME`. Credit to Thomas Kwa for finding it first!

```
length(Ans)+log(Ans≠"GOOGLE

```

(Guide: add 1 byte for each lowercase letter replacing an upper-case one. So `s/GOOGLE/google/g => +6 bytes`.)

### ahhhhh test cases!

```
"GOGGLE":prgmG
               6
"BING":prgmG
               4
"GOOGLE":prgmG
           Error

```

# Answer
> 27 votes
# Python 3, 30 bytes

```
lambda u:[len][u=='google'](u)

```

Indexes the 1-element function list, raising an `IndexError` if the `u=='google'` predicate is `True` (= 1). Such functional.

Much variants. Wow:

```
lambda u:[len(u)][u=='google']
lambda u:len([u][u=='google'])

```

> If the challenge was inverted (error on everything *not* "google"), could save a char:
>
> ```
> lambda u:{'google':len}[u](u)
>
> ```
>
> But you already know the length, so just hardcode it.

# Answer
> 24 votes
# APL (14)

```
(⍴÷'google'∘≢)

```

Explanation:

* : length
* `÷`: divided by
* `'google'∘≢`: argument is not equal to `'google'`.

gives the length of the string, which is divided by 1 if the string does not equal `google` (which gives the length back unchanged), or by 0 if the string *does* equal `google` (giving an error).

# Answer
> 20 votes
## Haskell, 24 bytes

`g s|s/="google"=length s`

Output:

```
Main> g "google"

Program error: pattern match failure: g "google"

Main> g "bing"
4

```

# Answer
> 18 votes
# Octave, 63 bytes

I know it is longer than the Matlab solution (which would work in Octave too), but it is particularly evil. I am making an anonymous function (evil) using cell array (evil) literals (evil) containing function handles dependent on a callback function (itself, thus recursive, evil) that must be passed via argument. Then I create another anonymous that basically reduces the function to the string argument and fixes the second argument of `f` as `f` (very evil). Any sane human would never do this, because it is almost as unreadable as Perl or regex (or cjam/pyth/any other esolang).

So if the string is not 'google' the second argument of the cell array will be called which outputs the length of the string. Otherwise the first function will be called, which is passed as a callback (and passes itself as callback to itself too) which later is the function itself. The error is basically some maximum recursion depth error.

```
f=@(s,f){@()f(s,f),numel(s)}{2-strcmp(s,'google')}();@(s)f(s,f)

```

# Answer
> 16 votes
# CJam, 16 characters

```
{_,\"google"=!/}

```

This divides the length by 1 if the string is not *google* and by 0 otherwise. The idea is not novel, but I came up with it independently.

Try it online.

### How it works

```
_                 Push a copy of the string on the stack.
 ,                Compute the length of the copy.
  \               Swap the length and the original string.
   "google"=      Push 1 if the string is "google", 0 otherwise.
            !     Apply logical NOT. Maps 1 to 0 and 0 to 1.
             /    Divide the length by the Boolean.

```

# Answer
> 14 votes
# APL, ~~19~~ 17 bytes

```
{⍵≡'google':⍟⋄≢⍵}

```

This is an unnamed monadic function that will throw a syntax error if the input is `google`. This is accomplished by attempting to take the natural logarithm of nothing.

```
{
 ⍵≡'google':          ⍝ If the right argument is "google"...
            ⍟⋄        ⍝ Compute log(<nothing>), which brings only sadness
              ≢⍵      ⍝ Otherwise compute the length
}

```

Try it online

Saved two bytes thanks to Dennis!

# Answer
> 12 votes
# JavaScript, 25 Bytes

Nice and simple JavaScript example:

```
e=>e!='google'?e.length:g

```

If "google" is entered then it passes a `ReferenceError`

Example

```
alert((e=>e!='google'?e.length:g)('test'))
```

# Answer
> 10 votes
# R, 46 bytes

```
g=function(x)ifelse(x!="google",nchar(x),)

```

Unless I'm misreading, the original post never specified that the code had to be correct syntax.

Example:

```
> g("bing")
[1] 4
> g("google")
Error in ifelse(x != "google", nchar(x), ) :
  argument "no" is missing, with no default

```

I never added anything for the "no" parameter of the ifelse statement so it will return an error if this parameter is evoked.

# Answer
> 10 votes
# Perl, ~~31~~ 29 bytes

```
sub{$_=pop;y///c/!/^google$/}

```

-2b thanks to manatwork

Usage:

```
sub{$_=pop;y///c/!/^google$/}->("google")

```

---

If I could get away with a program rather than a function, the following would be valid with only 20 bytes (+1 byte command line)

```
$_=y///c/!/^google$/

```

Error is division by zero.

Explanation:

`y///c` returns the length, then `!/^google$/` will return 0 iff input matches 'google'.

Usage:

```
perl -p entry.pl input.txt

```

# Answer
> 8 votes
# Java 7:~~53~~ 52 Bytes

```
int g(String _){return"google"==_?0/0:_.length();}

```

Above code will throw `ArithmeticException` for division by zero and for any `String` other than `google`. Worth to note that `==` compares reference and won't work for `String` Objects.

# Java 8 : 29 Bytes

(Based on suggestion given in below comment)

```
s->s=="google"?0/0:s.length()

```

# Answer
> 7 votes
## Haskell - 30 characters

```
g"google"=error"!";g s=length s

>g "google"
 *Exception: !
>g "str"
 3

```

# Answer
> 7 votes
# Python 3, 35 bytes

```
lambda n:len(n)if n!='google'else d

```

# Answer
> 7 votes
# C++11, 54 (code) + 14 (#include) = 68

Well, division by zero is just undefined behaviour, which I would not call an error. So my approach.

```
#include<ios>
[](std::string s){return s!="google"?s.size():throw;};

```

usage

```
[](std::string s){return s!="google"?s.size():throw;}("google");

```

# Answer
> 7 votes
# Ruby, 29 bytes

I first came up with something very similar to @Borsunho's first attempt, but mine was slightly longer and he posted his before I was done. Came up with this before his 30 bytes edit :)

```
->s{s[/^(?!google$).*/].size}

```

Usage examples:

```
$ irb
2.2.1 :001 > f = ->s{s[/^(?!google$).*/].size}
 => #<Proc:0x007fa0ea03eb60@(irb):1 (lambda)>
2.2.1 :002 > f[""]
 => 0
2.2.1 :003 > f["bing"]
 => 4
2.2.1 :004 > f["google"]
NoMethodError: undefined method `size' for nil:NilClass
  from (irb):1:in `block in irb_binding'
  from (irb):4:in `[]'
  from (irb):4
  from /Users/daniel/.rvm/rubies/ruby-2.2.1/bin/irb:11:in `<main>'

```

---

edit: Two years and some Ruby versions later

# Ruby, 25 bytes

```
->s{+s[/^(?!google$).*/]}

```

Replaced `String#size` with the new unary plus. Try it online!

# Answer
> 7 votes
**C, 66 48**

*Original:*

```
int l(long*s){return strlen(s)/((*s&~(-1L<<56))!=0x656c676f6f67);}

```

Using OSX gcc,
`l("duck");` returns `4`,
`l("google");` causes `Floating point exception: 8`.

On other platforms, the constants may need to be adjusted for endianness.

*Shorter*:

less trickyness, same results.

```
 l(int*s){return strlen(s)/!!strcmp(s,"Google");}

```

# Answer
> 6 votes
# MUMPS, 28 bytes

```
g(s) q $S(s'="google":$L(s))

```

Usage:

```
>w $$g^MYROUTINE("bing")
4
>w $$g^MYROUTINE("google")

<SELECT>g^MYROUTINE

```

Why? Well, `$S[ELECT]` is basically a compact multi-clause if-else statement - almost like a pattern-match in a language like Haskell or Rust. Except... unlike in Haskell or Rust, the patterns aren't checked for exhaustiveness, because the notion of "compile-time safety" is completely alien to MUMPS. So if your input is a pattern you didn't account for, you get a lovely runtime error called `<SELECT>`.

# Answer
> 6 votes
# JavaScript, 47 bytes

Nice and simple.

***Edit:*** Now complies with the rules

```
function f(g){if(g=="google")a;return g.length}

```

## Testing

### Error thrown

```
function f(g){if(g=="google")a;return g.length}

alert(f("Hello"))
alert(f("google"))
alert(f("hi"))
```

### No error thrown

```
function f(g){if(g=="google")a;return g.length}

alert(f("Hello"))
alert(f("bing"))
alert(f("hi"))
```

# Answer
> 5 votes
# Ruby, ~~34~~ ~~30~~ ~~27~~ 26

```
->x{x=='google'?t: x.size}

```

Unknown `t` raises exception.

```
->x{x=='google'?fail():x.size}

```

Edit: totally readable and obvious version that is shorter...

```
->x{x[x=~/^(?!google$)/..-1].size}

```

Old: Pretty similar to other ideas it seems. Will raise `ArgumentError` if x is 'google'.

# Answer
> 5 votes
# C - ~~99 75 67~~ 63 bytes

```
g(char*s){int i=0,j=*s;while(s[i])j^=s[++i];return j^9?i:g(s);}

```

## Ungolfed:

```
int g(char *s){
    int i = 0,
        j = s[0]; // first char of s
    while(s[i] != '\0'){
        j ^= s[++i]; // j = j XOR [next char]
    }
    if(j != 9){ // g^o^o^g^l^e = 9
        return i;
    } else {
        g(s); // infinite recursion
    }
}

```

Using it:

```
g("bing")       // 4
g("duckduckgo") // 10
g("google")     // segmentation fault

```

Will return the length if `g XOR o XOR o XOR g XOR l XOR e` isn't `9`, else it will infinite recurse causing a stack overflow.

## How it works

I used a (very) crappy hashing algorithm (`a XOR b XOR c ...`) to get a single number from the first six chars of the string. Collision likelyhood is very high, but if we assume the string has to be the name of an actual search engine, then the collision likelyhood is fairly low.

So, first we have `i`, which iterates through the string until `s[i]` is `NUL` (0), and while counting the length of the string, the selected char is XOR'd onto `j`, which is initialized to the first char in s. For "google", the result of this operation is 9.

The main thing this takes advantage of is the way pointers work in C. A pointer is actually a large number that denotes an address in memory, `&var` will return a pointer to `var`, while `*var` will dereference a pointer (grab the value at that address). Thus, `*s` is equivalent to `s[0]`. I think this is where most beginners get lost, confused and frustrated when it comes to C, like when you try to send a `struct *` to a function that takes `struct *` by sending `&struct_ptr`, which would be a memory address to a memory address, effectively making the compiler give an error such as `function expects 'struct *' but got 'struct **'`.

# Answer
> 5 votes
# Windows Batch, 118 characters

```
IF /I "%string%"=="google" exit
echo %string%> string.txt
for %%? in (string.txt) do ( SET /A stringlength=%%~z? - 2 )

```

Output is %stringlength%.

Full code:

```
@echo off
del string.txt
cls
echo Type your string
echo.
set /p string=String:
IF /I "%string%"=="google" goto err
echo %string%> string.txt
for %%? in (string.txt) do ( SET /A stringlength=%%~z? - 2 )
cls
echo %stringlength%
pause
del string.txt
:err
color c
echo There seems to be an error with your input...
pause>nul

```

Modified from Joshua Honig's answer, here.

# Answer
> 5 votes
# Japt, 14 bytes

```
U¥`goog¤`?Þ:Ul

```

Try it here!

### Explanation

```
U¥`goog¤`?Þ:Ul
U                     // U is the input
 ¥                    // ¥ is the Unicode shortcut for ==
  goog¤               // "google" compressed
 `      `             // backticks are used to uncompress goog¤
          Þ           // An undefined variable
            Ul        // l is a built-in that returns the length of U
                      // Implicit: output result of last expression

```

# Answer
> 5 votes
# Zsh, 18 bytes

```
<<<$#1>$1
<^google

```

Try it online!

Explanation:

* `<<<$#1`:
    + `$1`: the input
    + `#`: length
    + `<<<`: and print it
* `>$1`: redirect that output to a file called the input
* `^google`: try and find a file with any name other than `google`
* `<`: and print its contents

So if the file created was called `google`, then no file will be found and an error message will appear. But if the file was called anything else, then its contents is the length of the input, and it will be outputted.

# Answer
> 4 votes
# Common Lisp, ~~50~~ 48 bytes

```
(defun g(s)(if(equal s"google")(g s)(length s)))

```

Ungolfed:

```
(defun g(s)                ; Define a function g with one argument s
    (if (equal s "google") ; If s == "google",
        (g s)              ; Then recurse!
        (length s)         ; Else, return the length of s in characters
    )
)

```

Defines a function g that accepts one string as input. If it is not exactly 'google', then it returns the length. Otherwise, it will call itself on the same string, creating an infinite recursive loop and eventually causing a stack overflow error.

Usage (inside an interactive CLISP shell):

```
>(load "google.lsp")
Finished loading.
>(g "foo")
3
>(g "Lisp is cool!")
13
>(g "google")
*** - Program stack overflow. RESET

```

This is pretty long compared to the others, but using recursion seemed fitting for Lisp.

# Answer
> 4 votes
# GolfScript, ~~14~~ 16 Characters

```
{.,\'google'=!/}

```

Like many others, simply compares the input to `'google'` and divides the length by the inverse of the result.

Example programs:

# Answer
> 4 votes
## \>\<\>, 55 bytes

```
i:0(?v
31&l~<v0"google"~~.?%2l
$v?(2l<S?*=2l=6:+={
&<;n

```

Figured I'd give this a go, not my best golfing attempt or algorithm, though. Not a function per se, but I think that this should still qualify. I'll see if I can edit in a better version.

If you're allowed to print the length and then error, here's a 46 byte solution:

```
i:0(?v
2lnl~<v0"google";?%
$;?(2l<S?*=2l=6:+={

```

49 byte previous solution of this nature:

```
i:0(?v
l0nl~<v;!?=7
:;?(2l<S?*=2l=6:+=@@g3
elgoog

```

I'm happy to put up an explanation if there's any interest, and please let me know if there's anything wrong with my answer or if you have golfing suggestions.

# Answer
> 4 votes
## Javascript ES6, 51 27 25 bytes

Hi, I'm new to code golf so this can probably be golfed much more, but here it goes:

```
_=>_=="google"?a:_.length

```

`g=_=>_=="google"?a:_.length`

`g=_=>{if("google"==_)throw Error();return _.length}`

and some test:

```
(_=>_=="google"?a:_.length)("bing")//4
(_=>_=="google"?a:_.length)("google")// Error: a is not defined

```

```
g("bing")// returns 4
g("google")// Error: a is not defined

```

Edit: Added ? to replace if and replace Error with an undefined object.

Edit 2: I realized my byte count was wrong, and removed the g=

# Answer
> 4 votes
# Stuck, 16 Bytes

```
s_l1u"google"=-/

```

Following a similar method to most people, will cause a divide by 0 error on "google" being input.

# Answer
> 3 votes
# Matlab, 50 ~~51~~ bytes

*Thanks to @rayryeng for removing 1 byte*.

This uses an anonymous function, and exploits the fact that the `error` function with an empty input issues no error.

It's noteworthy that the error given for input `'google'` is *meta*: it's an error using the `error` function.

```
@(s)eval('error(find(strcmp(s,''google''))),numel(s)')

```

Examples:

```
>> @(s)eval('error(find(strcmp(s,''google''))),numel(s)')
ans =
    @(s)eval('error(find(strcmp(s,''google''))),numel(s)')
>> ans('abcd')
ans =
     4

>> @(s)eval('error(find(strcmp(s,''google''))),numel(s)')
ans =
    @(s)eval('error(find(strcmp(s,''google''))),numel(s)')
>> ans('google')
Error using error
The message must be specified as either a string or a message structure.
Error in @(s)eval('error(find(strcmp(s,''google''))),numel(s)')

```

# Answer
> 3 votes
# C# .NET, 65 bytes

```
int g(string s){return(s!="google")?s.Length:(1/int.Parse("0"));}

```

Test:

```
Console.WriteLine(g("str"));
Console.WriteLine(g("google"));

```

# Answer
> 3 votes
# PHP 5.4+, ~~40~~ 49 bytes

This one is quite unexpectedly long.

```
function g($x){echo[strlen($x),[]][$x==google];}

```

To run it, just pass a value:

```
g($argv[1]);

```

Test-cases:

> $php google.php googlea
> 7
> $php google.php google
> Notice: Array to string conversion in \[...\]\[...\] on line 1
> Array

I'm not sure if this can ve considered an error for this challenge or not.

---

One could use the over-used boring method:

```
function g($x){echo strlen($x)/$x==google;}

```

Which gives me a size of only 43 bytes.

---

As an alternative, one could use an exit error code, using the `exit` construct, for also 49 bytes:

```
function g($x){exit($x==google?strlen($x).'':1);}

```

All values between 1 and 254 are valid error codes that PHP uses when exiting.

# Answer
> 3 votes
## Perl 6, 19 bytes

```
{.comb/!/^google$/}

```

`.comb` returns list of characters in string (which in numeric context is a number of characters, I use this instead of `.chars` because it's shorter). Because there is nothing before a period, Perl 6 assumes you wanted to call a method on `$_`. This is divided by a negated match on regex `^google$` with implicit `$_` variable. If it matches, the value becomes 0, and Perl 6 errors because of a division by zero.

Example:

```
> {.comb/!/^google$/}("qwerty")
6
> {.comb/!/^google$/}("google")
Attempt to divide 6 by zero using div
  in any interactive at src/Perl6/Compiler.nqp line 62

```

# Answer
> 3 votes
# Scala, 48

```
def g(s:String)=if(s=="google")0/0 else s.length

```

To call:

```
 g("bing")      //> res1: Int = 4
 g("google")    //> java.lang.ArithmeticException: / by zero

```

# Answer
> 3 votes
# bash + coreutils, ~~57~~ ~~49~~ ~~38~~ ~~36~~ 33 bytes

```
[ "$1" = google ];expr ${#1} / $?

```

Calling it with `google` produces `expr: division by zero`.

The quotes around $1 are required in order to handle the empty string correctly.

The use of ${#1} is shamelessly stolen from Tarod's answer.

# Answer
> 3 votes
# O, 20 characters

```
{."google"={@}{.e}?}

```

Sample run:

```
bash-4.3$ java xyz.jadonfowler.o.O <( echo '{."google"={@}{.e}?} :f "yahoo" f o' )
5

bash-4.3$ java xyz.jadonfowler.o.O <( echo '{."google"={@}{.e}?} :f "google" f o' )
java.lang.ArrayIndexOutOfBoundsException: Can't pop from empty stack!
        at xyz.jadonfowler.o.Stack.pop(O.java:980)
        at xyz.jadonfowler.o.O.parse(O.java:407)
        at xyz.jadonfowler.o.CodeBlock.run(O.java:1031)
        at xyz.jadonfowler.o.O.parse(O.java:735)
        at xyz.jadonfowler.o.CodeBlock.run(O.java:1031)
        at xyz.jadonfowler.o.O.parse(O.java:99)
        at xyz.jadonfowler.o.O.runFile(O.java:37)
        at xyz.jadonfowler.o.O.main(O.java:20)
java.lang.ArrayIndexOutOfBoundsException: Can't pop from empty stack!
        at xyz.jadonfowler.o.Stack.pop(O.java:980)
        at xyz.jadonfowler.o.O.parse(O.java:425)
        at xyz.jadonfowler.o.O.runFile(O.java:37)
        at xyz.jadonfowler.o.O.main(O.java:20)

```

# Answer
> 3 votes
# Scala, ~~36 34 30~~ 29 characters

```
s=>(Set(s)-"google").max.size

```

Calling this function on "google" produces `java.lang.UnsupportedOperationException: empty.max`

# Answer
> 3 votes
# Japt, ~~16~~ 14 bytes

```
U¥`goog¤`?Δ:Ul

```

Throws reference error on input of `"google"`. Try it online!

# Answer
> 3 votes
# 05AB1E, 10 bytes

Code:

```
g“Š¹“¹Q</Ä

```

Explanation:

```
g           # Take the length of the implicit input
 “Š¹“       # Compressed version of "google"
     ¹Q     # Take the first input again and check if equal to "google"
       <    # Decrement on the bool
        /   # Divide the length by the value
         Ä  # Take the abstract value of the result
            # This is then implicitly printed

```

Try it online!. When the input is `google`, nothing is printed due to a division by zero exception.

# Answer
> 3 votes
# Java, ~~84~~ ~~68~~ 37 bytes

```
b->b.equals("google")?1/0:b.length();

```

This is a `java.util.function.Function<String, Integer>` that divides by 0 if `b` is the string `google`.

# Answer
> 3 votes
# Julia, 25 bytes

```
x->length(x)[x!="google"]

```

Try it online!

# Answer
> 3 votes
# Vyxal, 7 bytes

```
‛»Ǒ≠/÷L

```

Try it Online!

```
‛»Ǒ≠/÷L
‛»Ǒ     # "google"
   ≠    # ↑ != input
    /   # split input into ↑ even pieces. If input is "google", this will be 0, consequently causing an error
     ÷L # Get the length of the item

```

# Answer
> 3 votes
# Vyxal, 8 bytes

```
ɽ‛»¾=ßṀL

```

### Assumptions

* Program itself is the function g
* Program takes exactly one input

"Google" being in the code page dictionary allows for a 3 byte representation: ‛»¾

If input is equal to "google", case insensitive, will attempt to call a triad with too few arguments, else compute length.

Try it Online!

# Answer
> 2 votes
# CoffeeScript 43 bytes

```
(g)->return g.length if g!="google";throw-1

```

Makes an anonymous function that throws -1 if the string is `"google"`, and returns it's length otherwise. Not as obfuscated as I wanted, though.

Link to the online testing environment.

Another variation, 1 byte longer:

```
(g)->if g!="google"then g.length else throw-1

```

# Answer
> 2 votes
# PowerShell, ~~36~~ 35 Bytes

```
param($a)$a.length/($a-cne'google')

```

This blatantly abuses PowerShell's dynamic casting and uses xnor's trick for dividing by zero. In PowerShell, this is a *terminating error* and halts execution tossing a most excellently-verbose error <sub>(the error, at 242 characters, is over 6.5x the size of the function itself)</sub>

```
Attempted to divide by zero.
At line:1 char:11
+ param($a);$a.length/($a-cne'google')
+           ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], RuntimeException
    + FullyQualifiedErrorId : RuntimeException

```

*Saved a byte thanks to ConnorLSW*

# Answer
> 2 votes
# PHP 5.4, 81 bytes

```
<?function g($s){eval('if(isset('.($s==google?"$s":'$s').'))print strlen($s);');}
// following added for easy testing, not included in bytes count
g($argv[1]);

```

Everyone's favourite error when searching for Google! Didn't work out quite as obfuscated as I'd hoped...

Usage:

```
php 58891.php 'test'
4
php 58891.php 'google'
# error

```

# Answer
> 2 votes
## Lua, 42 Bytes

This challenge has made me realize how hard it is to cause an error in Lua.

```
x=io.read()print(x~="google"and #x or t())

```

Takes an input and if that input isn't google than print the length of the input, if not call a function t which doesn't exist, throwing an error.

# Answer
> 2 votes
# PARI/GP, ~~21~~ 19 bytes

```
x->#x/(x!="google")

```

Example:

```
? g = x->#x/(x!="google")
%1 = (x)->#x/(x!="google")
? g("bing")
%2 = 4
? g("google")
  ***   at top-level: g("google")
  ***                 ^-----------
  ***   in function g: #x/(x!="google")
  ***                    ^--------------
  *** _/_: impossible inverse in dvmdii: 0.
  ***   Break loop: type 'break' to go back to GP prompt
break>

```

# Answer
> 2 votes
## Prolog – 32 bytes

```
"google"*_:-x.
X*Y:-length(X,Y).

```

Defines a predicate `(*)/2` that throws `ERROR: */2: Undefined procedure: x/0` for the input "google":

```
?- "bing" * Length.
Length = 4.

?- "google" * Length.
ERROR: */2: Undefined procedure: x/0
   Exception: (8) x ? no debug

```

# Answer
> 2 votes
# PHP *error via a warning()*, 62, 52 46 bytes

I feel dirty for these, but it isn't about pretty:

```
function g($s){echo$s!=google?strlen($s):g();}

```

This will give "*Warning: Missing argument 1 for g()*" when you insert 'google', thought that was funny.

`function g($s){echo$s!=google?strlen($s):die(err);}`

`function g($s){if($s!=google){return strlen($s);}die(error);}`

# PHP *error as string*, 46 bytes

```
function g($s){echo$s!=google?strlen($s):err;}

```

String dont have to be quoted (but should be!)

---

You can run these via the commandline using `g($argv[1]);`, or via an older PHP version's `register_globals` method as an GET `g($_GET['string'])` or whichever :)

# Answer
> 2 votes
# rs, 31 bytes

```
^(google)|(.*)$/((^^\2))^^(1\1)

```

In rs, `^^` is the length and repetition operator. Used in the unary form, it will get the length of the following text `(^^\2)`. Used in binary form, it will repeat the LHS RHS times `((^^\2))^^(1\1)`.

Take the input `bing`. The input is not `google`, so the second group will match, not the first. Once the substitutions take place, the result is `((^^bing))^^(1)`. `^^` gets the length to result in `(4)^^(1)`, and the result gets repeated 1 time to result in `4`.

However, if the input is `google`, the first group will match. That will result in `((^^))^^(1google)` after substitutions. `^^` will just get the length of the empty string (0), so the result after `^^` is applied will be `(0)^^(1google)`. Now the repetition operator can do its work...or not. See it will try to repeat `0` `1google` times. As `1google` isn't a number, the output will be:

```
Traceback (most recent call last):
  File "c callback", line 6, in <module>
  File "<string>", line 5, in <module>
  File "<string>", line 167, in main
  File "<string>", line 125, in run
  File "<string>", line 72, in expand
ValueError: invalid literal for int() with base 10: '1google'

```

Live demo. (Put the input text in the box at the bottom left.)

# Answer
> 2 votes
# OCaml 42 bytes

This does exactly what is asked<sup>1</sup>: it returns a function which returns the length of its (string) argument, except when the argument is "google", in which case it fails with:

> Exception: Division\_by\_zero.

```
function"google"->0/0|s->String.length s;;

```

It doesn’t provide any way to actually *call* that function, though. In order to do that, you could either write:

```
(function"google"->0/0|s->String.length s)"some string";;

```

or you could, you know, give it a name.

```
let f=function"google"->0/0|s->String.length s;;
f"bing";;

```

Unpacked, this would give:

```
(* let f be function with one argument. *)
let f = function
    (* If the argument matches exactly "google", return 0/0 *)
    | "google" -> 0 / 0
    (* If no previous cases were a match, give your argument the name 'string'. *)
    (* and return its length. *)
    | string   -> String.length string
;;
(* Call f with "bing" as it’s argument. *)
f "bing";;

```

The type of `0 / 0` is `int`, so the function is correctly typed as `string -> int`.

---

1. Well, I must admit I have not checked these pesky Unicode details.

# Answer
> 2 votes
# C# 4.0, 51 bytes

`int g(string s){return s.Length/(s!="google"?1:0);}`

Sample:

```
string userInput = Console.ReadLine();
Console.WriteLine(g(userInput));

```

Output:

```
// "pogi" 4
// "google" DivideByZeroException was unhandled

```

# Answer
> 2 votes
# C++14, 47 bytes

```
[](auto s){return s=="google"?throw:s.size();};

```

This is a generic lambda expression in C++14. It simply checks if the argument (string) is "google" and calls `terminate` if it is - else it returns the length of the string.

It can be called as such:

```
[](auto s){return s=="google"?throw:s.size();}("some_string"s);

```

Zereges has a very similar answer here written in C++11. Since this was C++14 it was O.K. by him for me to post this.

# Answer
> 2 votes
## Befunge-93, 59 characters

```
<+1\_v#+1:~
vp00$<
<*_v#:\
v_v>$"google"*****-!#
< >00g.@>1

```

Befunge has no way to actually throw an error, so I just push an "infinite" number of 1s onto the stack. An error will happen *somewhere* eventually...

### Explanation

Anyway, this works by reading in the input and simultaneously keeping track of its length.

```
<+1\_v#+1:~

```

This length is stored at location `0,0`.

```
vp00$<

```

The remaining numbers are multiplied together.

```
<*_v#:\

```

This is then compared to the product of "google".

```
v_v>$"google"*****-!#

```

If they are the same (i.e., if their difference is zero), then the "error" is thrown. Otherwise, the value stored at `0,0` is retrieved and outputted.

```
< >00g.@>1

```

# Answer
> 2 votes
# , 17 bytes

```
{e\"google"=L@N?}
```

To use this function:

```
"wow" {e\"google"=L@N?} ~
```

Explanation:

```
e\               Get the length of the string and swap it on the stack
  "google"=      Compare the string
               ? If
            L@    True (it is google): Rotate top three elements on the stack, throwing an underflow error
              N   False (it is not google): do nothing
                   Length is printed out automatically

```

# Answer
> 2 votes
# Ruby, ~~46~~ ~~32~~ 29 bytes

```
->s{b=Hash.new(0);b['google']=nil;b[s]+s.size}

```

**New shortened approach:**

```
->g{(g.to_a-['google'])[0].size}

```

Reduced 3 bytes with manatwork's suggestion

```
->g{([g]-['google'])[0].size}

```

# Answer
> 2 votes
## AWK, 44 bytes

```
func f(x){return x=="google"?f(x):length(x)}

```

Example usages:

```
awk 'func f(x){return x=="google"?f(x):length(x)}{print f($0)}' <<< "non-google string"
awk 'func f(x){return x=="google"?f(x):length(x)}{print f($0)}' <<< "google"

```

Print: `17` and `Segmentation fault (core dumped)` respectively. The second one **may cause your computer to run out of memory before it segfaults** if you don't have oodles of RAM.

I find `Segmentation fault` errors to be a bit more broken than divide by zero since they don't even say where the problem is.

Something that looks more interesting would be:

```
func f(x){if(x=="google"){printf x;return f(x)}return length(x)}`

```

This would print `googlegooglegooglegoogle....` wrapping around the screen until it finally produces the seg. fault, but it's not as 'golfy'

NB. Yeah, I'm a bit late to the party, but nobody had an AWK answer yet. :)

# Answer
> 2 votes
# TI 89 BASIC, 34 bytes

I did this in TI 89 for fun. There has got to be a more optimized method, but this is the best I could come up with for the moment.

```
f(x)
getNum(x/"google")&""0+dim(x)

```

Basically abuses the fact that a string divided by itself becomes 1.

0 is necessary to remove the string from the calculation otherwise you would return ("fun" + 3) which i don't think is compliant to the rules.

# Answer
> 2 votes
# Julia, ~~26~~ 24 chars

Two characters shorter now, thanks to Dennis.

The challenge says **‘\[...\]in as few amount of Unicode characters as possible’**, so I’m going for  and  in my solution.

Anonymous function. Just assign it to a variable:

```
f->f≠"google"?endof(f):ℕ

```

In the case of "google" you get the error message:

```
julia> (f->f≠"google"?endof(f):ℕ)("google")
ERROR: UndefVarError: ℕ not defined

```

As ordinary function (26 chars):

```
x(f)=f≠"google"?endof(f):ℕ

```

is an unassigned variable, so it produces an error message. If that doesn’t count or is against the rules, then just using `!f` (one char longer) instead would produce an error anyway. Boolean not is not defined for strings.

# Answer
> 2 votes
# Fuzzy Octo Guacamole, 19 bytes (non-competing)

```
"google".^={e}_!r_;

```

`"google'` pushes the string "google" to the stack.

`.` swaps the active stack.

`^` gets input.

`=` is the rocketship operator, pushes `0` for equality, `-1` for less than, and `1` for greater than as `x <=> y` with `x` as the top of the active stack, and `y` as the top of the inactive one.

`{` and `}` denote an if statement, like bf's goto/if thing. Skips the code inside braces if the top of the stack is truthy.

`e` errors. That's it.

`_` pops the stack, this time is just to remove the equality check result and show the input.

`!` sets the universal register to the top of the stack, or the length of the top of the stack for strings/lists.

`r` clears the register and pushes it back to the stack.

`_` pops again, and

`;` prints.

So this checks for equality, then does a clumsy cast to int, and than prints the result.

# Answer
> 2 votes
# Gogh, 20 bytes

```
÷GD$"google"={¤+}¦:$

```

Usage:

```
./gogh o '÷GD$"google"={¤+}¦:$' "google"

```

---

### Explanation

```
             “ Implicit input                                              ”
÷            “ Duplicate the input                                         ”
GD           “ Push a range of [1, len(input)]                             ”
$            “ Rotate input to the TOS                                     ”
"google"=    “ Determine equality                                          ”
{¤+}¦:       “ Error if equals "google" (empties stack and tries addition) ”
$            “ Leave the length on the stack                               ”
             “ Implicit output                                             ”

```

# Answer
> 2 votes
# C++14, 42 chars

For giggles, as I did not see a very good c++ solution. My TI-89 solution is superior at 34 bytes

```
[](auto s){return s.size()/(s!="google");}

```

# Answer
> 2 votes
## Hoon, 32 bytes

```
|*
a/*
?<
=(a "google")
(lent a)

```

Uses a wet gate to avoid having to specify `a/tape` instead of `a/*`, assert that `a` doesn't equal "google" or panic, return the length of the tape.

```
> %.  "abc"
  |*
  a/*
  ?<
  =(a "google")
  (lent a)
3
> %.  "google"
  |*
  a/*
  ?<
  =(a "google")
  (lent a)
ford: build failed ~[/g/~dirdet-lasmes-digwyc-ribrux--rispyx-bitrus-bidmut-winsud/use/dojo/~dirdet-lasmes-digwyc-ribrux--rispyx-bitrus-bidmut-winsud/inn/hand /g/~dirdet-lasmes-digwyc-ribrux--rispyx-bitrus-bidmut-winsud/use/hood/~dirdet-lasmes-digwyc-ribrux--rispyx-bitrus-bidmut-winsud/out/dojo/drum/phat/~dirdet-lasmes-digwyc-ribrux--rispyx-bitrus-bidmut-winsud/dojo /d //term/1]

```

# Answer
> 2 votes
# Tellurium, 13 bytes

This language is newer than the question, so non-competing I guess.

```
i?google|d]L^

```

This program gets input using `i`, and checks if the input is "google". If it is, it tries dividing "google" by zero (`d`) well, that doesn't work (duh) so it throws an error.

If the input *isn't* google, it outputs the length of the selected cell's value (which is the input) using `L^`.

# Answer
> 2 votes
# JavaScript, 25 bytes

```
p=>p=='google'?_:p.length

```

# Answer
> 2 votes
# PHP, 48 bytes

```
eval((google==$s=$argv[1])."echo strlen(\$s);");

```

`php -r '<code>' google` --\>

**Parse error**: syntax error, unexpected 'echo' (T\_ECHO) \[...\] in eval()'d code on line **1**

---

**54 bytes for a function:**

```
function g($s){eval((google==$s).'echo strlen($s);');}

```

# Answer
> 2 votes
## PHP, 56 bytes

```
function google($i){echo strlen($i)/(__FUNCTION__!=$i);}

```

Yes, it's a bit long, but I feel this is really in the spirit of the question. You really mustn't google google when `google` is the actual function's name.

The constant `__FUNCTION__` holds the name of the function, which in this case is `google`. The rest of the functiondisplays the length of the input `$i` divided by 1 if `$i` is not `google`, or by 0 if it is. The latter throws an error.

Try it at Repl.it!

# Answer
> 2 votes
# 05AB1E, 8 bytes

```
g¹“Š¹“Ê÷

```

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

Explanation:

```
           # Implicit input
 g         # Take length
  ¹        # Get first input
   “Š¹“Ê   # != compressed form of "google"
        ÷  # Integer division (Zero Division Error if invalid)

```

# Answer
> 2 votes
# Jelly, 10 bytes

```
ßL⁼“æ8Ụ»$?

```

Try it online! (with `"google"` as input)

Try it online! (with `"bing"` as input)

## How it works

```
ßL⁼“æ8Ụ»$? - Main link. Argument: s (string)

         ? - if...
  ⁼     $  -   the input is equal to...
   “æ8Ụ»   -     "google"
           -   then
ß          -     call the main link (segfault)
           -   else
 L         -     return the length of the input

```

# Answer
> 2 votes
# Aceto, 19 bytes

```
rdM"google"J=$L€lp

```

Took me a while, but I finally got it. Aceto uses a hilbert curve for it's ip, which is really annoying.

```
r grabs input
d duplicates it
M pops the top value and stores it in quick memory
"google" pushes google on the stack, but with a lot of spaces in between.
- splits it on whitespace
J concatenates it
= pushes a bool on the stack: whether the top two values are equal
$ asserts that the top value is truthy, if not it raises an error.                                    Don't ask me why i don't have to negate it
L loads the quick memory
€ explodes the string, putting each char as a separate val on the stack
l takes the height of the stack
p prints that num

```

Try it online!

# Answer
> 2 votes
# Pyth - 15 bytes

```
?qz"google"'0lz

```

My favorite part of this is how I error. I use the `'` function which takes a string, but pass `0`, which is not a string.

# Answer
> 2 votes
# Brachylog, 12 bytes

```
"google"∧∈|l

```

Try it online!

Since Brachylog simply fails a predicate that tries to divide by 0, the error here comes from trying to unify the output with a list containing an entirely un-instantiated variable instead. If the input can be unified with `google`, it errors, and otherwise this predicate outputs the length of the input (add one more byte `w` to the end to make it a full program that prints the length).

# Answer
> 2 votes
## `d`, ~~10~~ 9 bytes

This is a full program but is technically also a function.

```
*↔XÑ║╜▄]ÿ

```

## Explanation

Decompressed:

```
-Fl'I`nakS/

```

After string decompression:

```
google"nakS/

```

```
google"n     # Does the input *not* equal to "google"?
        ak   # Find the length of the input
          S/ # Divide the length of the input by the above condition

```

# Answer
> 2 votes
# Clojure, ~~47~~ 44 bytes

**Old answer**

```
#(/(count %)(get{false 1 true 0}(= %"google")))

```

Try it online!

**New Answer**

```
#(/(count %)({false 1 true 0}(= %"google")))

```

Removed the get function call, because you can call a hashmap with a key to get the value.

Try it online!

# Answer
> 2 votes
# Red, 34 bytes

```
func[g][length? any[g ="google"g]]

```

Try it online! (the code so dense that it crashes the program).

# Answer
> 2 votes
# Python 3, 30 bytes

```
lambda x:len(x)//(x!="google")

```

Try it online! Python 3 port of xnor's Python 2 answer. The floor division operator is necessary to convert back to an integer instead of leaving it as a float.

# Answer
> 1 votes
## CoffeeScript, 36 bytes

```
f=(x)->throw 0if'google'==x;x.length

```

# Answer
> 1 votes
# jq, 39 characters

```
def g(s):s|length/({"google":0}[s]//1);

```

Sample run:

```
bash-4.3$ bin/jq -n 'def g(s):s|length/({"google":0}[s]//1); g("google")'
jq: error (at <unknown>): number (6) and number (0) cannot be divided because the divisor is zero

bash-4.3$ bin/jq -n 'def g(s):s|length/({"google":0}[s]//1); g("yahoo")'
5

```

On-line test:

# Answer
> 1 votes
# Emacs Lisp, 43 bytes

```
(lambda(s)(if(equal s"google")*(length s)))

```

Throws the error `(void-variable *)` for any string that equals `google`.

# Answer
> 1 votes
## STATA, 44 bytes

```
pr de a
if"google"==`0' f
di length(`0')
end

```

prints "unrecognized command: f" when input is "google"

# Answer
> 1 votes
# Perl5, 48 bytes

```
sub google{map{eval,-7+length}qq~&{"::$_[0]"}~}

```

google("google") and google will google("google").

Try it:

```
perl -e 'sub google{map{eval,-7+length}qq~&{"::$_[0]"}~} print google @ARGV' google

```

## 47 bytes

The following is one char shorter, but more fiddly on the command line:

```
sub google{map{eval,-6+length}qq~&{"'$_[0]"}~}

```

# Answer
> 1 votes
# F#, 33 Characters

```
function"google"->0/0|s->s.Length

```

When `"google"` is provided as input, it produces a `DevideByZeroException`.

Usage:

```
let g = function"google"->0/0|s->s.Length

g "bing"   // 4
g "google" // DivideByZeroException

```

# Answer
> 1 votes
# \>\<\>, 108 bytes

```
i:"g"=1-?v\]
i:"o"=1-?v\
i:"o"=1-?v\
i:"g"=1-?v\
i:"l"=1-?v\
i:"e"=1-?v\
i:01-=1-?v\
>i:0)?v~l n;
^     <  <

```

Try it here

# Answer
> 1 votes
# Java 1.8, 33 bytes

```
(s)->s.length()/(s=="google"?0:1)

```

## Explanation

The lambda takes a String named `s`, finds the length, and if it isn't "google", divides it by one, otherwise dividing it by zero and causing an Exception.

## Usage

Note that `java.util.function.Function` has to be imported.

```
Function<String, Integer> f = (s)->s.length()/(s=="google"?0:1); //Assign function to variable
    //Note that java type inferencing automatically handles the String type

System.out.println(f.apply("elgoog")); //Prints 6
System.out.println(f.apply("google")); //ArithmeticException: Divide by zero

```

# Answer
> 1 votes
# Lua, 47 bytes

```
print(assert(arg[1]~="google")and arg[1]:len())

```

Throws "assertion failed" if it's "google"

# Answer
> 1 votes
# golflua, 25 characters

```
\g(s)?s=="google"e""$~#s$

```

Sample run:

```
bash-4.3$ golflua -e '\g(s)?s=="google"e""$~#s$ w(g("google"))'
golflua: (command line):1:
stack traceback:
        [C]: in function 'e'
        (command line):1: in function 'g'
        (command line):1: in main chunk
        [C]: in ?

bash-4.3$ golflua -e '\g(s)?s=="google"e""$~#s$ w(g("yahoo"))'
5

```

# Answer
> 1 votes
# Clojure - 41 40 bytes

```
(defn g[s](if(= s"google")(g)(count s)))

```

Attempts to call itself with zero arguments for the input "google".

```
> (g "bing")
4
> (g "google")
clojure.lang.ArityException: Wrong number of args (0) passed to: sandbox10419$g

```

# Answer
> 1 votes
# PHP, 41 bytes

Because the division by zero is overused in the already existing answers, I tried to come up with something else (sacrificing 3 bytes):

```
<?=strlen($x=$argv[1])+log($x!="google");

```

It's not a function (the task explicitly asks to write a function) but it can be invoked from the command line in a functional manner:

```
$ echo '<?=strlen($x=$argv[1])+log($x!="google");' | php -- bing
4

$ echo '<?=strlen($x=$argv[1])+log($x!="google");' | php -- google
-INF

```

It doesn't produce an error when the argument is `google` but it doesn't display the length of the string `google` either. However it displays `-INF` (i.e. minus infinity) and this value can be considered an error for a function that returns a length (which, by definition, is a count, i.e. a non-negative number).

### A 38 bytes PHP solution using division by zero:

```
<?=strlen($x=$argv[1])/($x!="google");

```

It can be invoked in the same way as above. When the argument is `google` it displays a PHP warning.

# Answer
> 1 votes
# Swift, 71 Bytes

Short but lame:

```
print({assert($0 != "google");return $0.characters.count}(readLine()!))

```

Longer (75) but not lame:

```
print({{0/$0}($0.hash&-0x20f4f91ecf8d43)^$0.characters.count}(readLine()!))

```

The second one doesn't use any String literal. Works by subtracting the hash value of the input string by the "google" hashValue. Then it divides 0 by this value, resulting in a runtime error when it's `0` (`0/0 = undef.`) but in all other cases the result is `0` (`0/x = 0`). This result gets XOR'd by the character count in the String.

# Answer
> 1 votes
# Hassium, 52 Bytes

```
func g(s){if(s=="google")throw("");return s.length;}

```

Run and see expanded here

# Answer
> 1 votes
# Haskell, 24 characters

```
g n|n/="google"=length n

```

"Unexhaustive patterns" if you pass it "google".

# Answer
> 1 votes
## bash, 55 51 34 bytes

Thanks @manatwork!

```
[ "$1" != google ]&&echo ${#1}||0

```

It prints `command not found` if `$1` is `google`.

# Answer
> 1 votes
# C - 72 characters

```
g(char*s){char*p=s;for(;*p=="google"[p-s];p++);for(;*p;p++);return p-s;}

```

output:

```
g("test")    # 4
g("googles") # 7
g("google")  # Segmentation fault (core dumped)

```

This solution is pretty straightforward, no tricky bit manipulation (but also no library functions): match the string google in the first loop, and if there are still characters left continue to the end of the string. Return the difference between the pointers as the length.

The bug: given the string "google" the first loop does not terminate, causing it to overrun and dereference memory locations until it segfaults.

It also has a bonus bug: if you feed it the string "google\0" it succeeds but returns the wrong length.

# Answer
> 1 votes
# JS, 48 bytes

An improvement over Beta Decay's JS:

```
function f(g){g=="google"?g.s.s:alert(g.length)}

```

The original for reference:

```
function f(g){if(g=="google")throw 1;alert(g.length)}

```

# Answer
> 1 votes
## CoffeeScript, 32 bytes

```
g=(s)->(s if s!='google').length

```

To call:

```
g('bing') # returns 4
g('google') # TypeError: Cannot read property 'length' of undefined

```

The expression `(s if s!='google')` evaluates to `undefined` if the value of the argument `s` is `google`, otherwise it gives the argument itself. In the former case, JavaScript throws an error when attempting to access a property of `undefined`.

# Answer
> 1 votes
# Burlesque, 25 bytes

```
J"google"!={L[}j{vvg_}jie

```

Code can be run at Anarchy Golf checker. Click 'use form' choose 'burlesque', copy/paste code into the form, and input goes under it. Run.

# Answer
> 1 votes
XPath 2.0 (if you treat an XPath expression as a function with the context item as its argument):

Simple solution:

```
if (.='google') then error() else string-length()

```

If you treat returning an empty sequence as an error, then

```
string-length(.[.!='google'])

```

# Answer
> 1 votes
## **Go**: 92, 63, 59 bytes with panic instead of error

```
func g(s string)int{if s=="google"{panic(0)};return len(s)}

```

# Answer
> 1 votes
## PowerShell, 42 bytes

```
function g($x){$x.Length/($x-ne'google')}

```

# Answer
> 1 votes
# Powershell, 60

```
$f={param([string]$s);if($s-eq'google'){throw $s};$s.Length}

```

Usage:

```
PS> & $f google

```

Throws an exception.

```
PS> & $f bing

```

Returns 4

Shortest I could come up with :(

# Answer
> 1 votes
# Perl, ~~49~~ ~~46~~ ~~39~~ 31 bytes

```
sub g{sub g{$_=pop;y///c/!/^google$/}}

```

Call with `g(string)`, print with `print g(string)`.

**How it works**

The ternary operator only evaluates the expression if the condition is met. So when the input isn't `google`, it simply returns the original string and passes it on to `length`. However, is the input is `google`, it tries to divide by zero and causes this error:

```
Illegal division by zero at filename.pl line 1.

```

And as we all know, dividing by zero will break the internet (and the rest of reality).

**Changes**

* Saved 3 bytes by changing `return` to `print` and removing unneeded parentheses.
* Saved 6 bytes thanks to @manatwork, and saved an additional 1 byte by re-arranging my code.
* Saved 8 bytes and fixed an error thanks to @Grimy.

# Answer
> 1 votes
**ECMA6,30**

```
g=(s)=>s=="google"?-1:s.length

```

Since a string length of -1 is an error I think this is a valid answer in Javascript (ECMA6).

I was initially inspired by the python trick of causing a division by zero mentioned near the top. However this does not work in Javascript because you can divide by zero and get "Infinity" without throwing an error so I looked into other options.

This works in Chrome you can copy this into the dev console and then run it by calling g("some string here"). I assume any other browser that has partial support for ECMA6 should be able to run it.

# Answer
> 1 votes
# C++, 81

```
int l(char *s){int b=0,i=0;do{b=s[i]^"google"[i]?1:b;}while(s[i++]);return--i/b;}

```

Divides by 0 on "google". This is my first C++ golf, so any tips would be welcome.

`^` is used like `!=`. `b` is equal to `1` when the string is not `"google"`, `0` if it is. So `i/s` will result in `i/0`.

# Answer
> 1 votes
## **TSQL 2012, 87**

```
CREATE FUNCTION g(@p CHAR(9))RETURNS INT AS BEGIN RETURN IIF(@p='google',@p,LEN(@p))END

```

How to use :
SELECT dbo.g('gogle')
-- return 5

SELECT dbo.g('google')
--return Conversion failed when converting the varchar value 'google ' to data type int.

# Answer
> 1 votes
## AHK, 75 bytes

```
Inputbox,s
MsgBox % a(s)
a(b)
{
if (b!="google")
return StrLen(b)
throw b
}

```

there is no proper stdin and stdout support in ahk so im using inputbox and msgbox, the concept is the same tho.

# Answer
> 1 votes
# \>\<\>, 47 bytes

```
i:0(?\
?\ln;>~l6=
"\ "elgoog
!\{=?!\l ?
=< ;n6<

```

Here's a line-by-line breakdown:

```
i:0(?\

```

A standard \>\<\> input loop, pushes the input string followed by `-1`.

```
?\ln;>~l6=

```

Starts at `>`. Discards the -1, checks the length is equal to 6. If it is, move to next line, otherwise gets the length, prints, and exits.

```
"\ "elgoog

```

Starts at `\`. Pushes 'google' in reverse. If the input string was `google`, stack is now `googleelgoog`

```
!\{=?!\l ?

```

Starts at the first `\`. Rolls the stack one to the left. If top two elements aren't equal, moves to next line. Otherwise, if the stack is length is zero, the strings are equal, so also step to next line.

```
=< ;n6<

```

Starts on the 1st `<` if the string was 'google'. This is only reached when the stack is empty, so attempting to pop any number of values will cause an error - in this case, `=` is used. If the string wasn't 'google', outputs 6 and exits.

# Answer
> 1 votes
# J, 18

```
   #`^@.('google'-:])

```

Usage:

```
   #`^@.('google'-:]) 'googl'
5
   #`^@.('google'-:]) 'google'
|domain error
|       #`^@.('google'-:])'google'

```

Explanation

Count (`#`) if y does not match (`-:]`) the string `'google'`, but if it does match, compute e to the power of the string 'google', which is an error.

# Answer
> 1 votes
# Python, 47 bytes

```
a=input()
print(0/0 if a=="google" else len(a))

```

# Answer
> 1 votes
# Zsh and bc, 29 bytes

```
[ "$1" = google ];bc<<<$#1/$?

```

Sample output:

```
$ zsh not_google.sh oogle
5
$ zsh not_google.sh google
Runtime error (func=(main), adr=5): Divide by zero

```

## Explanation:

The first command exits true (zero) when the argument equals "google" and false (one) otherwise. That exit code is stored in `$?` until another command completes, allowing us to divide by that number.

We then run `bc` (with input via herestring) to compute the length of the argument divided by that exit code. This is either length ÷ 1 (the length) or length ÷ 0 (an error).

An un-golfed version:

```
if [ "$1" = google ]; then
  divisor=0
else
  divisor=1
fi
length="${#1}"
echo "$length / $divisor" |bc

```

---

# Bash and bc, 31 bytes

This uses the same logic, but `bash` can't handle `$#1` without braces:

```
[ "$1" = google ];bc<<<${#1}/$?

```

---

# Zsh and bc, 26 bytes (also errors on empty string)

This version also has an error when given an empty string, so I assume it doesn't count. It has the exact same output as the previous version (except when given an empty string or no argument).

```
bc<<<$#1/(0!=${#1#google})

```

## Un-golfed version of 26 byte answer:

```
length="${#1}"                 # the length of the first argument
unprefix_google="${1#google}"  # google → "", googler → r, goog → goog, "" → ""
length_unprefix_google="${#unprefix_google}"

if [ 0 != "$length_unprefix_google" ]; then
  divisor=1                # $unprefix_google is an empty string
else
  divisor=0                # $unprefix_google is not empty
fi

echo "$length / $divisor" |bc

```

# Answer
> 1 votes
# Go, ~~110~~ ~~102~~ ~~93~~ 92 bytes

It makes sense to use a language developed by Google employees to Google `Google`!

*note that this is actually a valid, compilable program, unlike the other go answer.*

~~will take input forever until "google" is input:~~

```
package main
import."fmt"
func main(){a:=""
Scan(&a)
if a=="google"{panic(0)}
Print(len(a))}
```

example i/o:

```
bing
4
oogle
5
google
panic: 0

goroutine 1 [running]:
runtime.panic(0x480e60, 0xc21000a190)
        /usr/lib/go/src/pkg/runtime/panic.c:266 +0xb6
main.main()
        /home/cat/projects/go/src/not-google/main.go:10 +0x115
exit status 2

```

ungolfed:

```
package main

import . "fmt"

func main() {
    a := ""
    Scan(&a)
    if a == "google" {
        panic(0)
    }
    Print(len(a))
}
```

apparently i had forgotten that `var a string` is just `""` aka empty string. sigh.

# Answer
> 1 votes
**MS T-SQL, 63 bytes**

```
CREATE PROC g @p CHAR(9) AS SELECT IIF(@p='google',1/0,LEN(@p))

```

Ungolfed code;

```
CREATE PROC g
    @p CHAR(9)
AS
    SELECT IIF(@p='google',1/0,LEN(@p))

```

Called by either EXEC g 'string' or simply g 'string'

Command: EXEC g 'gogle'

Result: 5

Command: EXEC g 'google'

Result: Msg 8134, Level 16, State 1, Procedure g, Line 1 Divide by zero error encountered.

# Answer
> 1 votes
# Milky Way 1.0.0, 18 bytes

This language was created after the challenge was posted.

```
'?{"google"b~z~y!}

```

---

### Explanation

```
'                   # read input from command line
 ?{         ~ ~  }  # if-else statement
   "google"         # push "google" to the stack
           b        # == on top two stack items (input and "google")
             z      # non-existent opcode raises an exception
               y    # push the length of the TOS to the stack
                !   # output the TOS

```

---

# Milky Way (current version), 18 bytes

```
'?{"google"b_z_y!}

```

---

### Usage

The code is called via the command line as follows:

```
./mw <path-to-code> -i <input>

```

# Answer
> 1 votes
## Java, 96 Bytes

This should work, but IDK for sure since I cant assess a computer at the moment:

Golfed:

```
 int g(String s){if(s.equals("google"))throw new
 IllegalArgumentException();return s.length();}

```

Ungolfed:

```
int g(String s){
    if(s.equals("google")) throw new IllegalArgumentException();
    return s.length(); }

```

I realize I could proably shorten this, let me know in the comments.

# Answer
> 1 votes
# Lua, 42 bytes

```
function g(s)return #(s~='google'and s)end

```

This creates a function g that takes an argument s and (assuming it is a string) returns the length (#) of the result of the evaluation `s~='google'and s`, which equates to s if s is not 'google', or false if it is. Since there is no length of false, if s is google, this will error, else, it will return the length. Simple and effective.

I know there are other Lua answers, and that I could shorten this by using io.read(), but I'm going to disregard both of those for the same reason: they don't actually use functions, like the question specifically calls for.

If I'm wrong in that it doesn't need to be a function, we can cut this to **32 bytes** by doing:

```
s=io.read()g=#(s~='google'and s)

```

# Answer
> 1 votes
# Mathcad, 23 "bytes"

And it even works with foreign languages ...

Note: Mathcad displays errors by showing the expression in red; clicking on the expression shows the error message.

# Answer
> 1 votes
# Rust, 41 chars

rust solution, provided by a friend who does have a rep of 10 to post (and asked me to post it on his behalf).

```
|x:str|{if x=="google"{panic!();}x.len()}

```

# Answer
> 1 votes
# TI-83 Basic, 21 bytes

Simple solution. (Lowercase tokens are two bytes each).

```
length(Ans)/(Ans≠"google

```

Alternate solution (22 bytes):

```
If Ans="google
.
length(Ans

```

Alternate solution (23 bytes):

```
length(Ans)+0/(Ans≠"google

```

# Answer
> 1 votes
# Molecule (v5.6+), 16 bytes

```
I_"google"=?p¿#

```

Explanation:

```
I_"google"=?p¿#
I_              duplicate
  "google"=     add google and compare
           ?p¿  if true, do a primality test on "google"
              # get length

```

This way the program will error and shutdown if it does a primality test on a string.

# Answer
> 1 votes
## Pyth, 12 bytes

```
/lznz"google

```

len(input())/input()!="google"

# Answer
> 1 votes
# Python 2, 46 bytes

```
a=raw_input()
print len(a)if a!='google'else b

```

Errors out on input of "google" because `b` is an undefined identifier, but succeeds on other strings since control never reaches `b` in those cases.

# Answer
> 1 votes
# Ruby, 26 bytes

Not shorter than the existing ones, but an alternative solution.

```
->x{(x=='google'||x).size}

```

If given `google`, it tries to do `true.size` which results in an error:

```
NoMethodError: undefined method `size' for true:TrueClass

```

# Answer
> 1 votes
## Clojure, ~~35~~ 33 bytes

```
#(/(count %)(if(= %"google")0 1))

```

---

```
(def g #(/(count %)(if(= %"google")0 1)))

(g "google")

ArithmeticException Divide by zero  clojure.lang.Numbers.divide

(g "bing")

4

```

Unfortunately, 0 is `true` is Clojure, and there aren't any simple ways of casting a bool to an int anyways, so I had to spend some bytes on a ternary. Still ended up being shorter than my first attempt.

V1: `#(if(= % "google")(/ 1 0)(count %)))`

# Answer
> 1 votes
# tcl, 46

```
proc x s {if \$s=="google" !;string length $s}

```

demo

# Answer
> 1 votes
# SmileBASIC, ~~41~~ 38 bytes

```
DEF G(S)RETURN LEN(S)/(S!="google")END

```

If `S` is not `google`, the length is divided by 1. Otherwise it's divided by 0, causing an error.

```
G("SAND")
4

G("google")
Divide by 0 in 0:1

```

# Answer
> 1 votes
# Edited processing JS: 68 bytes

```
var a =function(i){if(i==="google"){throw"a";}else{print(i.length);}};

```

Used a edited version of processing. When run here you can see it works. If you input google then the error buddy pops up without any message. This is my first golf!

Edited version of processing (didn't cheat by making my own version) https://github.com/Khan/processing-js

# Answer
> 1 votes
# Ruby, 19+1 = 20 bytes

Uses the `-n` flag. Because `-n` includes the trailing newline for any line of input, it must be piped in from a file w/o the trailing newline or it will not give the error and will instead return `7`.

```
p +~/(?<!^google)$/

```

Version that requires a trailing newline in the input, so you can type in directly from STDIN, for 20+1=21 bytes

```
p +~/(?<!^google)\n/

```

Alternate version that works with or without trailing newlines, for 23+1=24 bytes.

```
+(! ~/^google$/&&p~/$/)

```

All versions return the following error:

```
undefined method `+@' for nil:NilClass (NoMethodError)

```

# Answer
> 1 votes
## GNU sed, 137 bytes

Adding to the diversity of languages used here, I present a sed answer. There are no integer types or arithmetic operations in sed, so I wrote an increment method to get a string's length (111 bytes).

```
/^google$/{:;s:a*:&&a:;t}
s:^:0,:
:i
s:^9*,:0&:
s:.9*,:/&:;h
s:[0-9]*/::
y:0123456789:1234567890:
x;s:/.*::
G;s:\n::
s:,.:,:
/,./ti
s:,::

```

The first line of code checks if the input string is `google`, and if so it **continuously increases the pattern space until a memory allocation error is raised**. **Try it online!**

**Tests:** from a virtual Linux OS I setup with low memory

```
test@test:~$ sed -f google_error.sed <<< "yahoo"
5
test@test:~$ echo $?
0
test@test:~$ sed -f google_error.sed <<< "google"
sed: couldn't re-allocate memory
test@test:~$ echo $?
4

```

# Answer
> 1 votes
# C, 35 bytes

```
-Df(s)=strlen(s)/strcmp(s,"google")

```

Compiler flag :) Returns the length of the string provided. If it's `google` it throws a `Floating point exception`.

# Answer
> 1 votes
# Mathematica, 33 bytes

```
#=="google"&&1/0||StringLength@#&

```

TFW `Length` doesn't work on strings. \>.\>

# Answer
> 1 votes
# 05AB1E, 10 bytes

```
“Š¹“Qi.0ëg

```

Try it online!

---

```
“Š¹“       # Push "google".
    Qi   # If input == "google"...
      .0   # Divide by 0.
     ë   # Else...
      g    # Return length of input.

```

# Answer
> 1 votes
# Common Lisp, 50 bytes

```
(lambda(n)(assert(not(equal"google"n)))(length n))

```

Try it online!

# Answer
> 1 votes
# Stax, 9 bytes

```
ôK▓ÿσ▄Ω?╠

```

Run and debug online!

Well, defeated some of the 10-byters ...

## Explanation

Uses the unpacked version to explain.

```
`!:X9`|^hy%
`!:X9`         "google"
      |^       array xor (can't use `-` here, which means **set** difference)
        h      head of array, error if it is empty
         y%    length of input

```

# Answer
> 1 votes
# JavaScript (V8), 41 bytes

```
s=>s[['length']['google'==s|0]].toFixed()

```

Try it online!

# JavaScript (V8), 33 bytes

```
s=>[_=>s.length]['google'==s|0]()

```

Try it online!

# JavaScript (V8), 28 bytes

```
s=>[s]['google'==s|0].length

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 8 bytes

```
'Š¹QiFëg

```

Try it online!

```
'Š¹QiFëg  # full program
    i     # if...
          # implicit input...
   Q      # is equal to...
'Š¹       # "google"...
     F    # then...
          # (implicit) do nothing...
          # implicit input...
     F    # times
      ë   # else...
       g  # push length of...
          # implicit input
          # implicit output

```

# Answer
> 1 votes
# Racket, 46 bytes

```
(λ(x)(if(eq? x"google")(-)(string-length x)))

```

Try it online!

Gives an arity mismatch error on the input "google" since `-` needs at least one argument.

# Answer
> 1 votes
# Python 3.8 (pre-release), ~~37~~ 35 bytes

```
lambda s:len(s)if"google"!=s else~s

```

Try it online!

Reverted to this solution whilst comparing to the other answers and noticing that it was the same. -2 bytes thanks to the suggestion by Makonede to use `~s` instead of `s.s`

Raises `TypeError: bad operand type for unary ~: 'str'`

# Answer
> 1 votes
# Whispers v1, 53 bytes

```
> Input
> "google"
>> #1
>> 1≠2
>> 3÷4
>> Output 5

```

Try it online!

# Answer
> 1 votes
# Red, 46 bytes

```
func[a][(length? a)/ either a ="google"[0][1]]

```

Try it online!

My first attempt on writing something somewhat serious with Red

*sighs in boolean cannot be used as int*

# Answer
> 1 votes
# GNU sed, 102 bytes

I did stumble over this 137 byte `sed` solution, but besides the counting method can be improved the probably shortest way to produce an error with GNU `sed` is using the `e` flag to execute illegal code:

```
s/^google$/./e
s/.$/#/
:1
/#9*$/s/#/&0/
s/.9*$/_&/
h
y/0123456789/1234567890/
x
G
s/_.*_//
s/.//
/#/b1

```

Try it online!

Of course, you could save two more bytes using the buggy old version with empty labels.

# Answer
> 1 votes
# TypeScript's Type System, 113 (or 73) bytes

```
type F<I,S=I,L extends{}[]=[]>=S extends`${infer A}${infer B}`?F<I,B,[...L,A]>:I extends"google"?F<I>:L["length"]

```

Try it at the TypeScript playground!

Recursively take each character of the string and put it into a list. When no characters remain, check if the initial string was "google"; if so, recurse with the same initial string (i.e. recursion error), otherwise return the length of the list. (We must split the string into a list of characters because that's the only way to get the string's length in TypeScript's Type System.)

Or, by taking input as a tuple of characters instead of a string - 73 bytes:

```
type F<S extends{}[]>=S extends["g","o","o","g","l","e"]?F<S>:S["length"]

```

Try it at the TypeScript playground!

We can skip the whole recursive splitting process by taking the input directly as a list of strings, and comparing to the split string "google", with the same recursion error idea as the above.

# Answer
> 0 votes
# Groovy, 32 chars

```
e={(it=='google'?0:it).length()}

```

A similar approach like a bunch of others here. The closure tries to return the length of either

* the passed string, if it's not equal to `google`
* the length of the integer `0`, if the passed string is equal to `google`, which results in a MissingMethodException as there's no `Integer.length()` method

Tested with

```
e('bing')
e('google')
e('duckduckgo')

```

# Answer
> 0 votes
# Ruby, 41 characters

```
def g(s)puts s!="google"?s.length: a end

```

# Answer
> 0 votes
# Rust, 170 bytes

I didn't see anything in rust, so I figured I'd make one. Hopefully someone can improve this a bit! (or perhaps a byte... see what I did there ;) )

```
use std::io;fn main(){let s=io::stdin();let mut b=String::new();s.read_line(&mut b).unwrap();let l=b.len();b.truncate(l-2);assert!(b!="google");println!("{}", b.len());}

```

Throws the error:

```
thread '<main>' panicked at 'assertion failed: buffer != "google"', main.rs:7

```

when you try "google."

Ungolfed Code:

```
use std::io;
fn main() {
    let stdin = io::stdin();
    let mut buffer = String::new();
    stdin.read_line(&mut buffer).unwrap();
    let leng = buffer.len();
    buffer.truncate(leng-2);
    assert!(buffer!="google");
    println!("{}", buffer.len());
}

```

# Answer
> 0 votes
# Clojure (43 bytes)

I know Clojure has been answered before, and shorter too, but I love the way this one generates a StackOverflow error when "google" is passed in:

```
(defn f[s](if(= s "google")(f s)(count s)))

```

Example:

> user=\> (f "google")
>
> StackOverflowError user/f (NO\_SOURCE\_FILE:213)

# Answer
> 0 votes
# Powershell 34 Bytes

```
param($a)$a.length*($a-ne'google')

```

Multiply length by 0,1 boolean value of `not-equal` google.

Gives `0` if `google` (not case-sensitive), length otherwise.

# Answer
> 0 votes
# , 15 chars / 21 bytes (noncompetitive)

```
ï≔`google`?$:ïꝈ

```

`Try it here (Firefox only).`

# Answer
> 0 votes
# Game Maker Language, 60 bytes

```
a=argument0;if a="google"a=1/0show_message(string_length(a))

```

# Answer
> 0 votes
# ಠ\_ಠ, 110 bytes (noncompetitive)

```
ಠ_ಠ
ಠgoogleಠ
ಠ=ಠ
ಠ"ಠ
ಠ$ಠ
ಠ$ಠ
ಠ11ಠ
ಠ13ಠ
ಠ(ಠ
ಠ?ಠ
ಠ_ಠ
ಠ#ಠ
ಠ^ಠ

```

Try it here.

# Answer
> 0 votes
# Factor, ~~55~~ ~~53~~ 49 bytes

```
: g ( s -- l ) dup length swap "google" = not / ;

```

~~Throws the string "google". `throw` happens to be the same length as `0 0 /`. Or I could just divide a string by a number...~~ Or I could just divide the length of the string by if it's not `google`...

Example use:

```
cat @ mint-kitty : ~/projects/factor/factor(master??!) $ ./factor -run=listener
Factor 0.98 x86.64 (1742, heads/master-0bb3228063, Tue Mar 15 14:18:40 2016)
[Clang (GCC 4.2.1 Compatible Ubuntu Clang 3.6.2 (tags/RELEASE_362/final))] on linux
IN: scratchpad : dont-google ( str -- int ) dup "google" = [ throw ] [ length ] if ;
IN: scratchpad "bing" dont-google

--- Data stack:
4
IN: scratchpad "google" dont-google
google

Type :help for debugging help.

--- Data stack:
4
IN: scratchpad

```

The error in the UI:

# Answer
> 0 votes
# Scratch, 16 bytes

(scoring used)
Stopping the project is the closest thing to an error that I can get.

# Answer
> 0 votes
# C++, 77 Bytes

```
#include <string>
int G(std::string S){1/int(S!="google");return S.length();}

```

# Answer
> 0 votes
# Excel VBA, 52 Bytes

Subroutine that take input `a` as unassigned/variant of expected type variant/String and outputs to the VBE Immediates window. If `a` = "google" throws `Run-time error '3': Return without GoSub` else outputs the length of the input `a`.

```
Sub g(a)
If a="google"Then Return
Debug.?Len(a)
End Sub

```

# Answer
> 0 votes
# shortC, 21 bytes

```
Df(s)Ss)/Ms,"google")

```
* `Df(s)` defines a function `f` that takes one argument `s`.
* `Ss)` calculates the length of `s`.
* `Ms,"google)` compares `s` to "google".
* `Ss)/Ms,"google")` divides the length of `s` by `0` if the strings are equal. This throws `floating point exception` if they're equal.

Try it online!

# Answer
> 0 votes
# Syms, 18 bytes

```
{[#~{google}=!1/]}

```

Try it online!

# Answer
> 0 votes
# Bash

```
[ $1 == google ]; return $((${#1}/$?))

```

# Answer
> 0 votes
# GameMaker Language, 46 bytes

```
x=argument0
return string_length(x)/x!=google

```

Uses the same logic as this Python answer, abusing GMLs type coercion making the function divide by zero if the string equals google

I also haven't and can't test this because I currently don't have GameMaker installed, just made this from memory

# Answer
> 0 votes
# Keg, 16 bytes

```
:`google`=[0/|÷!

```

Try it online!

Attempt ruined by the fact that `google` isn't in Keg's dictionary. That's why I use DuckDuckGo, which at least has parts of it's name in the dictionary!

# Answer
> 0 votes
# Lua, 35 bytes

```
load'return #(...=="google"or ...)'

```

Try it online!

Idea is like one in @QuertyKeyboard's answer, but better optimized: `load` is used to create function and inverting check for "googleness" allows us to save one byte by replacing `and` with `or`.

Again, if full programs are allowed, we can cut down to **29** bytes!

# Lua, 29 bytes

```
print(#(...=="google"or ...))

```

Try it online!

# Answer
> 0 votes
# VBScript, 47 bytes

```
sub f(x)
msgbox len(x)/abs(x<>"google")
end sub

```

VBScript will return `-1` for `True`, so we have to `abs()` it. And attempts to divide it by the length, like the python answer.

# Answer
> 0 votes
# Knight, 17 bytes

```
O/L=gP!?g"google"

```

Try it online!

Requires a patch to fix an errata in the """golfed""" C interpreter, where it will leave a newline in the input from `PROMPT`. This matches the behavior of the AST interpreter and the wording of the spec.

This is the simple division by zero method.

```
# print length(g = prompt()) / (g != "google")
OUTPUT / (LENGTH(= g PROMPT)) (! (? g "google"))

```

Relies on division by zero throwing an exception. The AST interpreter will always throw an exception in software, but for the golfed interpreter, it requires the x86 behavior of throwing an exception on the hardware level.

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


# Question
Title: Find the longest permutations of integers from 1..k such that all neighbouring pairs sum to a square
OEIS A090461 details the ‘numbers k for which there exists a permutation of the numbers 1 to k such that the sum of adjacent numbers is a square’. This has also been the subject of Matt Parker’s Numberphile and Alex Bellos’ Monday puzzle.

This challenge is related to the square sum problem above and asks you to find the longest permutations of integers from 1 to k that have all of the neighbouring pairs sum to squares. Repetition is not allowed, but not all of the integers need to be used where this is impossible.

For example, when provided with the argument of `15`, the program should output `[[8, 1, 15, 10, 6, 3, 13, 12, 4, 5, 11, 14, 2, 7, 9], [9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8]]`. When provided with an argument of `8`, it should output `[[6, 3, 1, 8], [8, 1, 3, 6]]` (for 8, the longest possible permutation is only 4 numbers). All possible longest permutations should be output, but the order in which they are provided does not matter.

To expand on this further, for 15, first permutation given above is valid because `8 + 1 = 9` (32), `1 + 15 = 16` (42), `15 + 10 = 25` (52) and so forth.

The tag has been included to slightly increase the challenge and make brute forcing an answer less attractive. A valid entry should be able to return an answer for any single input from 3 to 27 within 60 seconds when run on tio or an equivalent environment. Otherwise, standard rules apply. This includes the standard input-output rules.

Interestingly, the sequence of lengths of such maximum-length permutations does not seem to have been posted on OEIS yet. I may subsequently post this there.

Further examples below. In each case, I’ve only given the first permutation for each input for brevity, but all of the valid ones should be returned.

For inputs less than 3, there are no valid answers but this does not have to be handled by your program or function. (You can assume there is at least one valid permutation.)

```
Input -> Output
2 -> any output or an error (does not have to be handled by your program or function)
3 -> [3,1] and 1 further permutation
4 -> [3,1] and 1 further permutation
5 -> [5,4] and 3 further permutations
6 -> [6,3,1] and 1 further permutation
7 -> [6,3,1] and 1 further permutation
8 -> [8,1,3,6] and 1 further permutation
9 -> [8,1,3,6] and 1 further permutation
10 -> [10,6,3,1,8] and 1 further permutation
11 -> [10,6,3,1,8] and 1 further permutation
12 -> [10,6,3,1,8] and 1 further permutation
13 -> [11,5,4,12,13,3,6,10] and 3 further permutation
14 -> [10,6,3,13,12,4,5,11,14,2,7,9] and 3 further permutation
15 -> [9,7,2,14,11,5,4,12,13,3,6,10,15,1,8] and 1 further permutation
16 -> [16,9,7,2,14,11,5,4,12,13,3,6,10,15,1,8] and 1 further permutation
17 -> [17,8,1,15,10,6,3,13,12,4,5,11,14,2,7,9,16] and 1 further permutation
18 -> [17,8,1,15,10,6,3,13,12,4,5,11,14,2,7,9,16] and 1 further permutation
19 -> [19,17,8,1,15,10,6,3,13,12,4,5,11,14,2,7,9,16] and 7 further permutations
20 -> [20,16,9,7,2,14,11,5,4,12,13,3,6,19,17,8,1,15,10] and 15 further permutations
21 -> [21,15,10,6,19,17,8,1,3,13,12,4,5,20,16,9,7,2,14,11] and 7 further permutations
22 -> [18,7,9,16,20,5,11,14,22,3,13,12,4,21,15,10,6,19,17,8,1] and 17 further permutations
23 -> [22,3,1,8,17,19,6,10,15,21,4,12,13,23,2,14,11,5,20,16,9,7,18] and 5 further permutations
24 -> [24,12,13,23,2,14,22,3,1,8,17,19,6,10,15,21,4,5,20,16,9,7,18] and 77 further permutations
25 -> [23,2,14,22,3,13,12,4,21,15,10,6,19,17,8,1,24,25,11,5,20,16,9,7,18] and 19 further permutations
26 -> [26,23,2,14,22,3,13,12,4,21,15,10,6,19,17,8,1,24,25,11,5,20,16,9,7,18] and 23 further permutations
27 -> [27,22,14,2,23,26,10,15,21,4,12,13,3,6,19,17,8,1,24,25,11,5,20,16,9,7,18] and 69 further permutations

```

# Answer
> 5 votes
# , 139 bytes

```
\(n,f=\(a,b,i=which(!(a+b[1])^.5%%1))`if`(sum(i),unlist(Map(\(i)f(a[-i],c(a[i],b)),i),F),list(b)))(a=f(1:n,{},1:n))[(l=lengths(a))==max(l)]

```

Attempt This Online!

**Ungolfed**

```
longest_perm_with_all_adjacent_squares=
function(n){

    # first define the recursive helper function f:
    f=function(a,b={}){
        # a is a vector of values that haven't been used yet, to choose the next value from;
        # b is the (initially empty) growing result containing only adjacent values that sum to squares

        if(length(b)==0)i=seq(along=a) else i=which(sqrt(a+b[1])%%1==0)
        # i is the vector of indices of a that we can use at each step

        if(length(i)==0)return(list(b))
        # if we can't use any more values from a, then just return the result-so-far

        else return(unlist(lapply(i,function(i)f(a[-i],c(a[i],b))),recursive=F))
        # otherwise, prepent each valid value from a to b, and perform a recursive call
    }

    # launch the helper function with the sequence 1..n in a, and leaving b empty by default:
    ans=f(1:n)

    # finally, select only the results with maximum length:
    ans[lengths(ans)==max(lengths(ans))]
}

```

# Answer
> 3 votes
# Jelly,  ~~29~~  26 bytes

```
0ịịḟ⁸⁸;Ɱ
²€_Ɱf€RɓW€ç€Ẏ¥ƬṖṪ

```

A monadic Link that accepts a positive integer greater than \\$2\\$ and yields all possible sequences of maximal length.

**Try it online!**

### How?

```
0ịịḟ⁸⁸;Ɱ - Link 1: list of ints, Sequence; list of lists of ints, Continuations
0ị       - last element of {Sequence}
  ị      - index into {Continuations} -> ints that will sum to a square
   ḟ⁸    - filter out elements of left argument (Sequence)
             -> removes those that would cause duplicates
     ⁸;Ɱ - concatenate each to left argument
             -> list of new, longer sequences (empty if none possible)

²€_Ɱf€RɓW€ç€Ẏ¥ƬṖṪ - Main Link: integer, k > 2
²€                - square each {[1..k]} -> [1, 4, 9, 16, ..., k²]
  _Ɱ              - subtract mapped across {[1..k]}
    f€R           - filter each keeping those in [1..k]
                      -> Continuations by current value:
                         [[3, 8, 15, ...], [2, 7, 14, ...], [1, 6, 13, ...], ...]
       ɓ          - start a new dyadic chain - f(k, ValidContinuations)
        W€        - wrap each of {[1..k]} -> [[1], [2], [3], ...]
              Ƭ   - start with Seqs=that and collect while distinct, applying:
             ¥    -   last two links as a dyad - f(Seqs, Continuations):
          ç€      -     call Link 1 as a dyad - f(Sequence, Continuations)
            Ẏ     -     tighten back to a list of sequences
               Ṗ  - pop -> removes the empty list found last
                Ṫ - tail -> maximal length sequences

```

---

#### 21 bytes (k=25)

Not brute force, but still times out for \\$k=26\\$:

```
W€;þẎ-.ịSÆ²ƲƇQƑƇʋƬRṖṪ

```

Try it online!

# Answer
> 3 votes
# APL (Dyalog APL), 37 bytes

```
{×≢n←⊃,/(⊂,¨⍺∩⊢~⍨(×⍨⍺)-⊢/)¨⍵:⍺∇n⋄⍵}⍨⍳

```

Attempt This Online!

Recursive approach, generates all results from 3 to 27 in a second.

# Answer
> 2 votes
# JavaScript (ES7), 137 bytes

```
f=(n,k=n)=>(P=(a,...p)=>o=p[a.map(v=>(++v+p[0])**.5%1||P(a.filter(x=>v+~x),v,...p)),k]?[...o,p]:o)([...Array(n).keys(o=[])])+o?o:f(n,k-1)

```

Try it online!

### Commented

```
f = (                 // f is a recursive function taking:
  n,                  //   n = input
  k = n               //   k = target permutation length (+1)
) => (                //
  P =                 // P is a recursive function taking:
      (a,             //   a[] = source array
          ...p) =>    //   p[] = permutation of a[]
  o = p[              //
    a.map(v =>        // for each value v in a[]:
      (++v +          //   increment v ([0..n-1] -> [1..n])
             p[0])    //   abort if v + p[0] ...
      ** .5 % 1 ||    //   ... is not a perfect square
      P(              //   otherwise, do a recursive call to P:
        a.filter(x => //     pass a copy of a[] ...
          v + ~x      //     ... where v is removed
        ),            //
        v, ...p       //     insert v at the beginning of p[]
      )               //   end of recursive call
    ),                // end of map()
    k                 // test p[k]
  ] ?                 // if it's defined:
    [...o, p]         //   append p[] to o[]
  :                   // else:
    o                 //   leave o[] unchanged
)([...Array(n).keys(  // initial call to P with a[] = [0..n-1]
  o = []              // and o[] initialized to an empty array
)]) + o ?             // if o[] is non-empty:
  o                   //   return it
:                     // else:
  f(n, k - 1)         //   try again with k - 1

```

# Answer
> 2 votes
# Python3, 238 bytes:

```
def f(k):
 q=[([i],{*range(1,k+1)}-{i})for i in range(1,k+1)]
 D={}
 while q:
  s,r=q.pop(0)
  if len(s)>1:D[len(s)]=D.get(len(s),[])+[s]
  for i in range(1,int((2*k)**0.5)+1):
   if(K:=i**2-s[-1])in r:q+=[(s+[K],r-{K})]
 return D[max(D)]

```

Try it online!

# Answer
> 2 votes
# Charcoal, 55 bytes

```
≔…·¹Ｎθ≔ＥθΦ⁻Ｘθ²ι№θληＵＭθ⟦ι⟧ＦθＦ⁻§η⊖↨ι⁰ι⊞θ⁺ι⟦κ⟧⪫Φθ⁼ＬιＬ§θ±¹¶

```

Try it online! Link is to verbose version of code. Program was originally more efficient but I slowed it down slightly in the name of code golf, but not so much that it can't easily solve `n=27` on TIO. Explanation:

```
≔…·¹Ｎθ

```

Make a range from `1` to `n`.

```
≔ＥθΦ⁻Ｘθ²ι№θλη

```

For each element of that range, make a list of all valid adjacent numbers.

```
ＵＭθ⟦ι⟧

```

Wrap each element of that range in a list so that it can be the first element of a potential permutation.

```
Ｆθ

```

Loop over all potential permutations.

```
Ｆ⁻§η⊖↨ι⁰ι

```

Loop over all remaining next valid adjacent numbers.

```
⊞θ⁺ι⟦κ⟧

```

Add the new permutation to the list.

```
⪫Φθ⁼ＬιＬ§θ±¹¶

```

Output all permutations of maximal length.

# Answer
> 2 votes
# Python 3.8, 127 bytes

```
f=lambda k,p=0:(r:=range(1,k+1))and(c:=[l+[v]for l in p or[[i]for i in r]for v in r if(l[-1]+v)**.5%1==(v in l)])and f(k,c)or p

```

**Try it online!**

# Answer
> 2 votes
# Ruby, 120 bytes

```
->n{r=z=w=[*1..n];r,w=w,r.flat_map{|b|(z-[*b]).map{|a|[a,*b]}}.reject{|a|b=0;a.any?{|a|b*(b+b=a)**0.5%1>0}}while w[0];r}

```

Try it online!

# Ruby, 96 bytes

```
f=->n,z=n{w=[*1..n].permutation(z).reject{|a|b=0;a.any?{|a|b*(b+b=a)**0.5%1>0}};w[0]?w:f[n,z-1]}

```

Try it online!

Super-slow, times out for n=11.

# Answer
> 2 votes
# JavaScript (Node.js), 109 bytes

```
f=(n,s=[[]],t=[])=>s.map(x=>(g=n=>n&&g(n-1,(n+x[0])**.5%1||x.includes(n)||t.push([n,...x])))(n))|t<f?s:f(n,t)

```

Try it online!

# JavaScript (Node.js), 106 bytes

```
n=>f=(s=[[]],t=[],i=n)=>i?s.map(x=>(i+x[0])**.5%1||x.includes(i)||t.push([i,...x]))&&f(s,t,--i):t<f?s:f(t)

```

Try it online!

# Answer
> 2 votes
# , 99 bytes

```
\(n){a=b=1:n;while(length(g<-unlist(Map(\(y)lapply(setdiff(b[!(b+y[1])^.5%%1],y),c,y),a),F)))a=g;a}

```

Attempt This Online!

Hopefully this is a suitable interval before posting my own answers to my challenge. This is an anonymous function that takes a single numeric argument `n` and returns a list of integer vectors.

## Ungolfed

```
join_lists <- function(x) {
  unlist(x, recursive = FALSE)
}
find_max_ss_permutations <- function(n) {
  # Initialize two vectors a and b with numbers from 1 to n
  a <- b <- 1:n

  # Iterate while there are permutations with adjacent numbers summing to squares
  while ({
   g <- join_lists(lapply(a, function(y) {
    # Filter elements from b where adjacent numbers sum to squares
    filtered_b <- setdiff(b[!(b + y[1])^.5 %% 1], y)

    # Extend existing vector with filtered elements
    lapply(filtered_b, function(item) c(item, y))
    }))
    length(g)
  }) {
    # Update a with the new permutations
    a <- g
  }

  # Return the longest possible permutations satisfying the square sum condition
  return(a)
}

```

Attempt This Online!

---
Tags: code-golf, number, sequence, restricted-time
---


title: Array Factorization

text:
# Question
Title: Array Factorization
Given an array of positive integers, output a stable array of the distinct prime factors of these integers. In other words, for each integer in the input in order, get its prime factors, sort them, and append any primes not already in the output to the output.

# Test Cases

```
[1,2,3,4,5,6,7,8,9,10] -> [2,3,5,7]
[10,9,8,7,6,5,4,3,2,1] -> [2,5,3,7]
[100,99,98,1,2,3,4,5] -> [2,5,3,11,7]
[541,60,19,17,22] -> [541,2,3,5,19,17,11]
[1,1,2,3,5,8,13,21,34,45] -> [2,3,5,13,7,17]
[6,7,6,7,6,7,6,5] -> [2,3,7,5]
[1] -> []
[8] -> [2]
[] -> []

```

Output can be as an array or list of integers or strings, delimited output, or any other standard means of outputting an ordered list of numbers.

This is , so shortest answer in bytes wins.

# Answer
> 9 votes
# 05AB1E, 3 bytes

Outputs as a list of Strings.

```
f˜Ù

```

Try it online!

# 2sable, 3 bytes

Yes, this also works in 2sable. Also returns a list of Strings.

```
f˜Ù

```

Try it online!

# Answer
> 5 votes
# Husk, 3 bytes

*1 byte saved thanks to @Zgarb.*

```
uṁp

```

Try it online!

---

# Explanation

```
uṁp    Full program.

  p    Prime factors of each.
 ṁ     Map function over list and concatentate the result.
u      Unique.

```

# Answer
> 5 votes
# Bash + GNU utilities, 37

* 21 bytes saved thanks to @muru (wow!)

```
factor|tr \  \\n|awk '!/:/&&!a[$0]++'

```

Try it online.

# Answer
> 4 votes
# Pyth, ~~5~~ 4 bytes

```
{smP

```

**Try it here!** or **Verify all test cases.**

Alternative: `{sPM`

---

# Explanation

```
{smP      Full program with implicit input (Q).
  m       Map over the input.
   P      Prime factors.
 s        Flatten.
{         Deduplicate.

```

# Answer
> 4 votes
# MATL, 6 bytes

```
"@Yfvu

```

Try it online!

Explanation:

```
"      % Loop over input
 @     % Push the array element
  Yf   % Prime factors
    v  % Concatenate entire stack vertically (does nothing the first iteration)
     u % Stably get distinct (unique, in MATLAB terminology) elements. Does so every loop but this is code golf, not fastest code.

```

Interesting MATL tidbits: generally, all functions apply to vectors (arrays) just as easily. But in this case, the number of factors is variable for each input, and Matlab and by extension MATL generally only deal in square matrices, so I had to use a for loop `"`.

Furthermore, MATL has two main concatenation operators: `h` and `v`, horizontal and vertical concatenation. Their behaviour differs significantly: `v` concatenates the entire stack, even if it has only one element like in our first iteration. `h` takes exactly two elements and will fail if only one is present, making it unsuitable for this application.

# Answer
> 4 votes
# Brachylog, 6 bytes

```
ḋᵐ↔ᵐcd

```

**Try it online!**

# Brachylog, 6 bytes

```
ḋᵐoᵐcd

```

**Try it online!**

---

## Explanation

```
ḋᵐ       Map  with prime decomposition (which returns the factors in reverse order).
  ↔ᵐ     Reverse each (or oᵐ - order each).
    c    Concatenate (flatten).
     d   Deduplicate.

```

# Answer
> 3 votes
# Jelly, ~~5~~ 4 bytes

1 byte thanks to clap.

```
ÆfFQ

```

Try it online!

# Answer
> 3 votes
# PowerShell, 102 bytes

```
param($x)$a=@();$x|%{$a+=(2..($z=$_)|?{!($z%$_)-and'1'*$_-match'^(?!(..+)\1+$)..'}|sort)};$a|select -u

```

Try it online!

*(Borrows factorization idea from TessellatingHeckler's answer over on "Get thee behind me Satan-Prime!")*

Takes input as a literal array `$x`. Creates a new empty array `$a`. Loops over `$x`. Each iteration we loop from `2` up to the current number, checking whether that is a factor `-and` is prime, then `|sort` the output of that, and append it to `$a`. When we're done going through `$x`, we then output `$a` but `|select` only the `-u`nique numbers thereof. This exploits the fact that the uniqueify goes left-to-right, keeping the first occurrence, which matches the problem description. Those numbers are left on the pipeline and output is implicit.

# Answer
> 3 votes
# CJam, 11 bytes

```
{:mfe__&1-}

```

Function that takes array of ints and outputs array of ints.

Test Version

# Answer
> 3 votes
# Gaia, 4 bytes

```
ḍ¦_u

```

Try it online!

---

# Explanation

```
ḍ¦      Prime factors of each.
  _     Flatten the list.
   u    Remove duplicate elements.

```

# Answer
> 2 votes
# Pyke, 4 bytes

```
MPs}

```

Try it here!

---

# Explanation

```
MP       Prime factors of each.
  s      Flatten.
   }     Deduplicate.

```

# Answer
> 2 votes
# Mathematica, 64 bytes

```
Select[DeleteDuplicates[First/@FactorInteger@#~Flatten~1],#>1&]&

```

**input**

> \[{100, 99, 98, 1, 2, 3, 4, 5}\]

# Answer
> 2 votes
# Japt, 6 bytes

```
mk c â

```

Test it

---

## Explanation

Implicit input of array `U`. Map (`m`) over it, getting the factors (`k`) of each element. Flatten (`c`), get the unique elements (`â`) and implicitly output.

# Answer
> 2 votes
# Haskell, 77 bytes

```
import Data.List
x!y|y>x=[]|x`mod`y<1=y:(x`div`y)!y|1<2=x!(y+1)
nub.((!2)=<<)

```

### Explanation:

* the `x!y` operator returns a list of all prime factors of `x` that are greater than or equal to `y`
* the `(!2)` function returns a list of all prime factors of its argument
* the function on the last line implements the required functionality

Try it online.

# Answer
> 2 votes
# Brachylog, 6 bytes

```
ḋᵐoᵐcd

```

Try it online!

### Explanation

```
ḋᵐ         Map prime decomposition
  oᵐ       Map order
    c      Concatenate
     d     Remove duplicates

```

# Answer
> 2 votes
# Ohm v2, 3 bytes

Yet another 3-byter (thanks to languages with auto-vectorization).

```
m{U

```

**Try it online!**

---

# Explanation

```
m      Prime factors. Auto-vectorizes over the input.
 {     Flatten.
  U    Uniquify.

```

# Answer
> 2 votes
# Python 3, ~~128 125~~ 116 bytes

This is a pure Python solution. No packages. *Thanks to Halvard for saving 9 bytes.*

```
def f(l):y=[k for i in l for k in range(2,i+1)if i%k<1*all(k%x for x in range(2,k))];print(sorted({*y},key=y.index))

```

Try it online!

# Python 2, ~~133 127~~ 126 bytes

```
def f(l):y=sum([[k for k in range(2,i+1)if i%k<1*all(k%x for x in range(2,k))]for i in l],[]);print sorted(set(y),key=y.index)

```

Try it online!

# Python 2, ~~142 138~~ 134 bytes

```
l=input();r=[]
for i in sum([[k for k in range(2,i+1)if i%k<1*all(k%x for x in range(2,k))]for i in l],[]):r+=[i]*(i not in r)
print r

```

Try it online!

Very surprised there was no Python answer yet. Working on golfing.

# Answer
> 2 votes
# Deorst, 16 bytes

```
EDkE]EQFPkl1FeE_

```

Try it online!

Done with help from @Mr.Xcoder. This is way too long for a pseudogolfing language.

### How it works

```
EDkE]EQFPkl1FeE_ - Full program, implicit input: [1,2,3,4,5]

ED               - Get divisors. Vectorizes. STACK = [[1], [1,2], [1,3], [1,2,4], [1,5]]
  k              - Turn off sorting for the next command
   E]            - Flatten the stack. STACK = [1, 1, 2, 1, 3, 1, 2, 4, 1, 5]
     EQ          - Deduplicate stack in place. STACK = [1, 2, 3, 4, 5]
       FP        - Filter by primality 1 is considered prime. STACK = [1, 2, 3, 5]
         k       - Turn off sorting for the next command
          l1     - Push 1. STACK = [1, 2, 3, 5, 1]
            Fe   - Filter elements that are equal to the last element. STACK = [2, 3, 5]
              E_ - Output the whole stack

```

# Answer
> 2 votes
# Deorst, 16 bytes

```
EDkE]l1FeFPkEQE_

```

Try it online!

Done with help from @cairdcoinheringaahing in the Deorst chatroom (note that the solutions are different).

---

# Explanation

```
EDkE]l1FeFPkEQE_   Full program.

ED                 Push the list of divisors of each element.
  k                Prevent the stack from reordering.
   E]              Flatten the stack.
     l1Fe          Remove 1s from the stack (because caird rushed and made 1 prime!) - Should be removed in future language releases.
         FP        Keep the primes.
           k       Prevent the stack from reordering.
            EQ     Deduplicate.
              E_   Output the result.

```

# Answer
> 2 votes
# Vyxal, 3 bytes

```
ǐfU

```

Try it Online!

```
ǐ   # prime factors
 f  # flattened
  U # uniquified

```

# Answer
> 2 votes
# Ruby `-rprime`, 50 bytes

```
->x,*r{x.map{_1.prime_division.map{|b,|r|=[b]}};r}

```

Attempt This Online!

# Answer
> 1 votes
# Pyke, 4 bytes

```
mPs}

```

Try it here!

```
mP   -   map(factorise, input)
  s  -  sum(^)
   } - uniquify(^)

```

# Answer
> 1 votes
# Octave, 61 bytes

```
a=input('');b=[];for c=a(a>1)b=[b setdiff(factor(c),b)];end;b

```

Try it online!

# Answer
> 1 votes
# MY, 17 bytes

```
⎕Ḋḟ’⊢f(‘53ǵ'ƒf(ū←

```

Try it online!

## How?

* evaluated input
* divisors (vectorizes/vecifies)
* flatten
* `’⊢f(‘` decrement, filter, increment (removes `1`)
* `53ǵ'` the string `'P'` in MY's codepage, which is primality testing. Sadly `0x35=53` is the 16th prime number, and there's not a command for pushing `16` to the stack \>\_\< .
* `ƒ` as a function
* `f(` filter by that
* `ū` uniquify
* output

# Answer
> 1 votes
# C++, 118 bytes

```
[](auto n){decltype(n)r;for(int m:n)for(int i=1,j;i++<m;){j=m%i;for(int x:r)j|=!(i%x);if(!j)r.push_back(i);}return r;}

```

Needs to be passed the input in a `std::vector<int>`, returns another `std::vector<int>` for output.

# Answer
> 1 votes
# J, 10 bytes

```
~.(#~*),q:

```

I'm sure some clever J-er could make this shorter.

# Answer
> 1 votes
## Python 2, ~~88~~ ~~119~~ 103 bytes

Here we go. With the correct sorting.

```
def f(l,s=[]):[s.append(x) for x in sum([list(primefac(i)) for i in l],[]) if x not in s];print s
from primefac import*

```

Apperently I can't get it to work on TIO, because the package is not supported. It does run on my machine tho. Here are my Test outputs:

```
f([1,2,3,4,5,6,7,8,9,10],[])     #[2, 3, 5, 7]
f([10,9,8,7,6,5,4,3,2,1],[])     #[2, 5, 3, 7]
f([100,99,98,1,2,3,4,5],[])      #[2, 5, 3, 11, 7]
f([541,60,19,17,22],[])          #[541, 2, 3, 5, 19, 17, 11]
f([1,1,2,3,5,8,13,21,34,45],[])  #[2, 3, 5, 13, 7, 17]
f([6,7,6,7,6,7,6,5],[])          #[2, 3, 7, 5]
f([1],[])                        #[]
f([8],[])                        #[2]
f([],[])                         #[]

```

Somehow I was not able to make the function as a lambda-function. Whenever i try to return the list comprehention, it returns \[None, None, ...\]. If i am just overlooking something, could someone point that mistake out? Thanks for the feedback!

---

Edit:

Using Mr. Xcoders sorting algorithm I could cut down the code by 16 bytes. Thank you for that part.

```
from primefac import*
def f(l):a=sum([list(primefac(i))for i in l],[]);print sorted(set(a),key=a.index)

```

# Answer
> 1 votes
# Braingolf, 7 bytes

```
&(p)u=;

```

Try it online!

Oh look, it's *basically* a chain of 4 built-ins

## Explanation

```
&(p)u=;  Implicit input from commandline args
 (.)     Sandbox loop, sandboxes each item in a separate stack and runs the
         code within the loop.
&        Append the entire sandboxed stack when loop ends, rather than only the
         top of stack after each iteration
  p      Prime factors
    u    Unique
     =   Print stack
      ;  Suppress implicit output

```

# Braingolf v2, 5 bytes

```
&pu=;

```

Try it online!

Braingolf's v2 interpreter doesn't have the "sandbox loop" `(.)` implemented yet, however due to more consistent modifier behavior, it's not needed for this challenge, as the greedy `&` modifier works directly on the prime factors `p` instruction, causing it to factorize every item on the stack.

# Answer
> 1 votes
# Actually, 5 bytes

```
♂y♂i╔

```

Try it online!

Explanation:

```
♂y♂i╔
♂y     prime factors of each element
  ♂i   flatten
    ╔  deduplicate (stable)

```

# Answer
> 1 votes
# APL (Dyalog Extended), 4 bytesSBCS

```
∪∘∊⍭

```

Try it online!

# Answer
> 1 votes
# Factor \+ `math.primes.factors`, 32 bytes

```
[ [ factors ] map-flat members ]

```

Try it online!

* `factors` Get the prime factors of a number.
* `map-flat` Apply a quotation to each member of a sequence, collecting the (non-scalar) results in a flat sequence of the same length.
* `members` Remove duplicates.

---
Tags: code-golf, array, primes
---