# Question
Title: Find the smallest number that doesn't divide N
This challenge is simple enough that it's basically all in the title: you're given a positive integer **N** and you should return the smallest positive integer which is not a divisor of **N**.

An example: the divisors of **N = 24** are `1, 2, 3, 4, 6, 8, 12, 24`. The smallest positive integer which is not in that list is **5**, so that's the result your solution should find.

This is OEIS sequence A007978.

## Rules

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

You may use any programming language, but note that these loopholes are forbidden by default.

This is , so the shortest valid answer – measured in *bytes* – wins.

## Test Cases

The first 100 terms are:

```
2, 3, 2, 3, 2, 4, 2, 3, 2, 3, 2, 5, 2, 3, 2, 3, 2, 4, 2, 3, 2, 3, 2, 5, 2,
3, 2, 3, 2, 4, 2, 3, 2, 3, 2, 5, 2, 3, 2, 3, 2, 4, 2, 3, 2, 3, 2, 5, 2, 3,
2, 3, 2, 4, 2, 3, 2, 3, 2, 7, 2, 3, 2, 3, 2, 4, 2, 3, 2, 3, 2, 5, 2, 3, 2,
3, 2, 4, 2, 3, 2, 3, 2, 5, 2, 3, 2, 3, 2, 4, 2, 3, 2, 3, 2, 5, 2, 3, 2, 3

```

In particular, make sure that your answer works for inputs **1** and **2** in which case the result is larger than the input.

And for some larger test cases:

```
N          f(N)
1234567    2
12252240   19
232792560  23

```

## Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

```
/* Configuration */

var QUESTION_ID = 105412; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/<a/.test(lang)) lang = jQuery(lang).text();

    languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang > b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
```

```
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<div id="language-list">
  <h2>Winners by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
```

# Answer
> 21 votes
# Mathematica, 19 bytes (UTF-8 encoding)

```
1//.x_/;x∣#:>x+1&

```

Unnamed function taking a nonzero integer argument and returning a positive integer. The vertical bar about halfway through is actually the three-byte character U+2223, which denotes the divisibility relation in Mathematica. Explanation:

```
1                   Starting with 1,
 //.                apply the following rule until it stops mattering:
    x_                if you see a number x
      /;x∣#           such that x divides the function argument,
           :>x+1      replace it with x+1.
                &   Cool, that's a function.

```

Edited to add: ngenisis points out that `//.` will, by default, iterate a maximum of 65536 times. So this implementation works for all input numbers less than the least common multiple of the integers from 1 to 65538 (in particular, on all numbers with at most 28436 digits), but technically not for all numbers. One can replace `x//.y` with `ReplaceRepeated[x,y,MaxIterations->∞]` to fix this flaw, but obviously at the cost of 34 additional bytes.

# Answer
> 16 votes
## JavaScript (ES6), ~~25~~ 23 bytes

```
f=(n,k)=>n%k?k:f(n,-~k)

```

*Note:* One interesting thing here is that the `k` parameter is initialized *ex nihilo* on the first iteration. This works because `n % undefined` is `NaN` (falsy as expected) and `-~undefined` equals `1`. On the next iterations, `-~k` is essentially equivalent to `k+1`.

### Test

```
f=(n,k)=>n%k?k:f(n,-~k)

// first 100 terms
for(i = 1, list = []; i <= 100; i++) {
  list.push(f(i));
}
console.log(list.join(' '));

// larger test cases
console.log(f(1234567));
console.log(f(12252240));
console.log(f(232792560));
```

# Answer
> 15 votes
## Pyth, 3 bytes

```
f%Q

```

Basically, `f` loops the code until `%QT` (`Q % T` where `T` is the iteration variable) is true.

Try it online here.

# Answer
> 14 votes
# Hexagony, 12 bytes

```
\\)?}'@{!%.}

```

Embiggened:

```
   \ \ )
  ? } ' @
 { ! % . }
  . . . .
   . . .

```

Try it online!

# Answer
> 13 votes
# Python, 43 36 35 bytes

```
f=lambda n,d=2:d*(n%d>0)or f(n,d+1)

```

# Answer
> 11 votes
# R, 28 bytes

Pretty straightforward, nothing fancy. Takes input from stdin, increments value `T` until `i` modulo `T` is nonzero.

```
i=scan()
while(!i%%T)T=T+1
T

```

If you want something a little more fancy, there's the following for **29 bytes**:

```
i=scan()
match(0,!i%%1:(i+1))

```

Explained:

> `i=scan()` : Read `i` from stdin.
>
> `1:(i+1)` : Generate all integers from `1` to `i+1` (the `+1` accounting for the cases of `1` and `2`).
>
> `i%%1:(i+1)` : Modulo the input by every number in our list.
>
> `!i%%1:(i+1)` : Negate the resulting list; this implicitly converts it to a logical type, such that `0` is `FALSE` and nonzero is `TRUE`. After negating, `TRUE` values become `FALSE` and vice-versa. Now, all originally nonzero values are coded as `FALSE`.
>
> `match(0,!i%%1:(i+1))` : Return the index of the first instance of `0` in our list. `0` is `FALSE`, so this returns the index of the first `FALSE` in the list, which is the first nonzero value from the modulo operation. Since our original list began at `1`, the index is equal to the value of the smallest non-divisor.

# Answer
> 10 votes
## Haskell, 26 bytes

```
f n=until((>0).mod n)(+1)1

```

Everyone forgets about `until`!

# Answer
> 9 votes
# Brachylog, 10 bytes

```
~{=#>:A'*}

```

Try it online!

This came out very similar to (but shorter than) Fatalize's original solution. Fatalize has since switched to a different algorithm that ties with this one via a different method, so I'm going to have to explain it myself:

```
~{=#>:A'*}
~{       }    inverse of the following function:
  =           try possible values for the input, if it's unbound
   #>         the input is a positive integer
     :A'*     there is no A for which the input times A is the output

```

When we invert the function, by swapping "input" and "output", we get a fairly reasonable algorithm (just expressed in an awkward way): "try possible positive integers, in their natural order (i.e. 1 upwards), until you find one that can't be multiplied by anything to produce the input". Brachylog doesn't do floating-point calculations unless all inputs are known, so it'll only consider integer A.

# Answer
> 9 votes
# COW, 174 bytes

```
oomMOOMMMmoOmoOmoOMMMmOomOoMoOMMMmoOmoOmoOMMMmOoMOOmoO
MOomoOMoOmOoMOOmoOmoomoOMOOmOoMoOmoOMOomoomOomOoMOOmOo
moomoOMOomoomoOmoOMOOmOomOomOomOoOOMOOOMOomOOmoomOomOo
mOomOomOomoo

```

Try it online!

This code is only partially my own -- it implements a modulus algorithm that I ported from brainfuck. The rest of the code is my own. However, since I did not write the modulus algorithm, I haven't truly investigated how it works and cannot document that part of the code. Instead, I'll give my usual breakdown, followed by a more in-depth explanation of why the code works.

## Code breakdown

```
oom                          ;Read input into [0].
MOO                          ;Loop while [0].  We never change [0], so the program only terminates forcibly after a print.
  MMMmoOmoOmoOMMMmOomOo      ; Copy [0] to [3] and navigate to [1].
  MoOMMMmoOmoOmoOMMM         ; Increment [1], and copy it to [4]
  mOo                        ; Navigate back to [3].
  MOO                        ; Modulus algorithm.  Direct port of brainfuck algorithm.
    moOMOomoOMoOmOo
    MOO
      moO
    moo
    moO
    MOO
      mOoMoOmoOMOo
    moo
    mOomOo
    MOO
      mOo
    moo
    moOMOo
  moo                        ; End modulus algorithm.
  moOmoO                     ; Navigate to [5].  This contains our modulus.
  MOO                        ; Only perform these operations if [5] is non-zero -- i.e. [0] % [1] != 0
    mOomOomOomOoOOMOOOMOomOO ;  Navigate to [1], print its contents, then error out.
  moo                        ; End condition
  mOomOomOomOomOo            ; Since we're still running, [0] % [1] == 0, so navigate back to [0] and try again.
moo                          ;End main loop.

```

## Explanation

The code first reads the integer into \[0\]. Each iteration of the main loop (lines 2 through 26) increments \[1\], then copies everything necessary over to the modulus algorithm, which spits out its result into \[5\]. If \[5\] contains any value, then \[1\] is the number we need to print. We print it, and then force-quit the program.

Since COW is a brainfuck derivative, it functions relatively similar to the way brainfuck operates -- infinite strip of tape, you can move left or right, increase or decrease, and "loop" while the current tape value is non-zero. In addition to brainfuck, COW comes with a couple of useful features.

```
(0) moo -- Equivalent to ]
(1) mOo -- Equivalent to <
(2) moO -- Equivalent to >
(3) mOO -- No equivalent.  Evaluate current tape value as instruction from this list.
(4) Moo -- If tape is 0, equivalent to ,; if tape is non-zero, equivalent to .
(5) MOo -- Equivalent to -
(6) MoO -- Equivalent to +
(7) MOO -- Equivalent to [
(8) OOO -- No equivalent.  Set tape (positive or negative) to 0
(9) MMM -- No equivalent.  If register is empty, copy tape to register.  If register is non-empty, paste register to tape and clear register.
(10) OOM -- No equivalent.  Print an integer from tape to STDOUT
(11) oom -- No equivalent.  Read an integer from STDIN and store it on tape

```

The real point of interest here is instruction 3, `mOO`. The interpreter reads the current tape value, and executes an instruction based on that tape value. If the value is less than 0, greater than 11, or equal to 3, the interpreter terminates the program. We can use this as a quick-and-dirty force quit of the main loop (and the program entirely) once we've found our non-divisor. All we have to do is print our number, clear \[1\] (with `OOO`), decrement it to -1 with `MOo`, and then execute instruction -1 via `mOO` which ends the program.

The tape itself for this program functions as follows:

```
[0]  -- Read-in integer from STDIN.
[1]  -- Current divisor to test
[2]  -- Placeholder for modulus algorithm
[3]  -- Temporary copy of [0] for use for modulus algorithm
[4]  -- Temporary copy of [1] for use for modulus algorithm
[5]  -- Placeholder for modulus algorithm.  Location of remainder at end of loop.
[6]  -- Placeholder for modulus algorithm
[7]  -- Placeholder for modulus algorithm

```

The modulus algorithm naturally clears \[2\], \[3\], \[6\], and \[7\] at the end of the operation. \[4\]'s contents get overwritten with the register paste on line 4, and \[5\] is zero when \[0\] is divisible by \[1\], so we don't have to clear it. If \[5\] is non-zero, we force-quit on line 23 so we don't have to worry about it.

# Answer
> 8 votes
# Brachylog, ~~11~~ 10 bytes

```
,.=:?r'%0'

```

Try it online!

### Explanation

```
,.=           Assign an integer to the output
 . :?r'%0     Input mod Output ≠ 0
        0'    Output ≠ 0

```

# Answer
> 7 votes
# 05AB1E, 7 bytes

```
Xµ¹NÖ_½

```

Try it online!

**Explanation**

```
Xµ       # run until counter is 1
  ¹      # push input
   N     # push iteration counter
    Ö_   # push input % iteration counter != 0
      ½  # if true, increase counter
         # output last iteration

```

# Answer
> 7 votes
# C, ~~32~~ 35 bytes

```
i;f(x){for(i=1;x%++i<1;);return i;}

```

*Edit: added `i=1` in the loop*

### Usage

```
main(c,v)char**v;{printf("%d",f(atoi(*++v)));}

```

### Full Program version, 64 Bytes:

```
main(c,v)char**v;{*++v;for(c=1;atoi(*v)%++c<1;);printf("%d",c);}

```

# Answer
> 7 votes
# Jelly, 5 bytes

```
1%@#Ḣ

```

Try it online!

Explanation:

```
1%@#Ḣ
1  #      Find the first … numbers, counting up from 1, such that
 %@       dividing those numbers into … gives a truthy remainder
    Ḣ     then return the first

```

This is a horrendous abuse of `#`; there are plenty of operators in this program, but a ton of missing operands. `#` really wants the `1` to be given explicitly for some reason (otherwise it tries to default to the input); however, everything else that isn't specified in the program defaults to the program's input. (So for example, if you give 24 as input, this program finds the first 24 numbers that don't divide 24, then returns the first; kind-of wasteful, but it works.)

# Answer
> 6 votes
# C#, ~~39~~ 37 bytes

```
n=>{int i=0;while(n%++i<1);return i;}

```

Saved two bytes thanks to Martin!

# Answer
> 6 votes
# Octave/MATLAB, ~~26~~ 24 bytes

```
@(n)find(mod(n,1:n+1),1)

```

`find(...,1)` returns the index (`1`-based) of the first nonzero element of the vector in the first argument. The first argument is `[n mod 1, n mod 2, n mod 3, n mod 4,...,n mod (n+1)]` That means we have to add `+1` to the index, since we start testing at `1`. Thanks @Giuseppe for -2 bytes.

Try it online!

# Answer
> 6 votes
# 05AB1E, 6 bytes

```
ÌL¹ÑK¬

```

Try it online!

Also, it spells "LINK!"... Kinda...

```
ÌL     # Push [1..n+2]
  ¹Ñ   # Push divisors of n.
    K¬ # Push a without characters of b, and take first item.

```

# Answer
> 6 votes
# Jelly, 5 bytes

```
‘ḍ€i0

```

Try it online!

### How it works

```
‘ḍ€i0  Main link. Argument: n

‘      Increment; yield n+1.
 ḍ€    Divisible each; test 1, ..., n+1 for divisibility by n.
   i0  Find the first index of 0.

```

# Answer
> 5 votes
# Jelly, 6 bytes

```
%R;‘TḢ

```

Try it online!

Explanation:

```
                                               Assume 24 is our N
 R      Generate all numbers from 1 to N         [1, 2, 3, 4 .., 24]
  ;‘    Attach N+1 to that list (for cases 1,2)  [1, 2, 3, 4 .., 25]
%       And modulo-divide our input by it
        Yields a list with the remainder         [0, 0, 0, 0, 4 ...]
    T   Return all thruthy indexes               [5, 7, ...]
     Ḣ  Takes the first element of that list -->  5

```

# Answer
> 5 votes
## Perl, 19 bytes

18 bytes of code + `-p` flag.

```
$_=$_%++$.?$.:redo

```

To run it:

```
perl -pE '$_=$_%++$.?$.:redo' <<< 12252240

```

*Not very detailed* explanations:
\- `$.` is a special variable whose default value is the current line number of the last filehandle accessed (stdin here), so after reading the first line of input, it's set to 1.
\- `$_` holds the input and is implicitly printed at the end (thanks to `-p` flag).
\- `redo` (in that context) considers that the program is in a loop and redo the current iteration (only `$.` will be different since it got incremented).
\- So if we found the smallest number (stored in `$.`) that doesn't divide `$_`, then we set `$_` to it, otherwise, we try the next number (thanks to `redo`).

# Answer
> 5 votes
## Python 2.7.9, 32 bytes

```
f=lambda n,d=1:n%d>0or-~f(n,d+1)

```

Test on Ideone

Recursively counts up potential non-divisors `d`. It's shorter to recursively the increment the result than to output `d`. An offset of `1` is achieved by the Boolean of `True`, which equals `1`, but since `d==1` is always a divisor, the output is always converted to a number.

Python 2.7.9 is used to allow allow `0or`. Versions starting 2.7.10 will attempt to parse `0or` as the start of an octal number and given a syntax error. See this on Ideone.

# Answer
> 5 votes
# Perl 6, 17 bytes

```
{first $_%*,1..*}

```

Try it

## Expanded:

```
{  # bare block lambda with implicit parameter ｢$_｣

  # return the first value
  first

  # where the block's argument ｢$_｣ modulus the current value ｢*｣
  # doesn't return 0 ( WhateverCode lambda )
  $_ % *,
  # ( ｢$_ !%% *｣ would be the right way to write it )

  # from 1 to Whatever
  1 .. *
}

```

# Answer
> 3 votes
# julia, 28 bytes

```
N->findfirst(x->N%x>0,1:N+2)

```

Note: since `1:N+2` doesn't allocate memory there is no memory problems for large `N` s
\- @flawr `N+2` save for me some bytes
\- @Martin 's suggestion saved 1 bytes

# Answer
> 3 votes
# Actually, 7 bytes

```
;÷@uR-m

```

Try it online! (note: this is a very slow solution, and will take a long time for large test cases)

Explanation:

```
;÷@uR-m
;÷       duplicate N, divisors
  @uR    range(1, N+2)
     -   set difference (values in [1, N+1] that are not divisors of N)
      m  minimum

```

# Answer
> 3 votes
# Haskell, 29 bytes

```
f n=[k|k<-[2..],mod n k>0]!!0

```

The expression `[k|k<-[2..]]` just creates an infinite list `[2,3,4,5,...]`. With the condition `mod n k>0` we only allow those `k` in the list that do not divide `n`. Appending `!!0` just returns the first entry (the entry at index `0`) form that list.

Try it online!

# Answer
> 3 votes
# Dyalog APL, 8 bytes

```
1⍳⍨0≠⍳|⊢

```

`1⍳⍨` position of first True in

`0≠` the non-zero values of

`⍳|` the division remainders of 1...**N** when divided by

**N**

TryAPL online!

Note: this works for 1 and 2 because `1⍳⍨` returns 1 + the length of its argument if none is found.

# Answer
> 3 votes
# PHP, 30 bytes

```
for(;$argv[1]%++$i<1;);echo$i;

```

if run from console with `-r` option (thx to @ais523)

```
php -r 'for(;$argv[1]%++$i<1;);echo$i;' 232792560

```

# 32 bytes

```
<?for(;$argv[1]%++$i<1;);echo$i;

```

thanks to @manatwork for removing 1 byte

# 33 bytes (original)

```
<?for(;$argv[1]%++$i==0;);echo$i;

```

# Answer
> 3 votes
## QBIC, 14 bytes

```
:[a+1|~a%b|_Xb

```

Explanation:

```
:      Read the first cmd line param as a number, called 'a'
[a+1|  FOR (b=1 ; b <= a+1; b++) <-- a+1 for cases a = 1 or 2
~a%b   IF A modulo B ( == 0, implicit)
|_Xb   THEN exit the program, printing b
       [IF and FOR implicitly closed by QBIC]

```

# Answer
> 3 votes
# C, 30 bytes

Recursion is your friend:

```
f(x,i){return x%i?i:f(x,i+1);}

```

Call as follows:

```
#include <stdio.h>

f(x,i){return x%i?i:f(x,i+1);}

int main() {
    for(int i = 1; i < 10; i++) {
        printf("f(%d, 1) = %d\n", i, f(i, 1));
    }
}

```

# Answer
> 3 votes
# Cubix, ~~14~~ 12 bytes

```
I2/L/);?%<@O

```

Saved 2 bytes thanks to MickyT.

Try it

### Explanation

In cube form, the code is:

```
    I 2
    / L
/ ) ; ? % < @ O
. . . . . . . .
    . .
    . .

```

Basically, this just takes the input and starts a counter. It then checks each successive value of the counter until it finds one that isn't a factor of the input.

# Answer
> 3 votes
# Rust, 23 bytes

```
|n|(1..).find(|x|x%n>0)

```

Try it online!

A closure that iterates over all positive integers returning `Some(n)` where n is the first integer modulo input is greater than zero.

# Answer
> 3 votes
# convey, <sup>20</sup> 18 bytes

*-2 thanks to Jo King!*

```
 >!/|!`!}
{"^."^[1

```

Try it online!

The values follow the arrow heads. `{` gets the `N`, here 24. This value is `"` duplicated and both values are then merged into `!`: repeat 24 for 24 times. The 24s go the right, while their indices are pushed down. Then `index | 24` (mod) is calculated (for dividers this is 0). We repeat the corresponding index for `i | 24` times, thus dividers get deleted. 5 on the other hand will be repeated 5 times. As we only want 1 of them, we take `!` only 1 of them. The rest of the values build up and when nothing moves, the factory comes to a halt. Here is an ungolfed variant.

# Answer
> 2 votes
## \>\<\>, 15 +3 = 18 bytes

```
1\n;
?\1+:{:}$%

```

Input is expected to be on the stack at program start, so +3 bytes for the `-v` flag. Try it online!

# Answer
> 2 votes
## Jellyfish, ~~12~~ 10 bytes

```
p\~~|1
 >i

```

Takes input from STDIN and outputs to STDOUT. Try it online!

Martin Ender saved 2 bytes, thanks!

## Explanation

```
 \~~|
 >i

```

This part is one function that uses the input value in its definition.

```
   ~|

```

This `~`-cell is given a function, so it flips its arguments: its produces the binary function "left argument modulo (`|`) right argument". The built-in modulo function in Jellyfish takes its arguments in the reverse order.

```
  ~~|
  i

```

This `~`-cell is given a value and a function, so it does partial application: it produces the binary function "input (`i`) modulo right argument". Let's call that function **f**.

```
 \~~|
 >i

```

The `\`-cell is given two functions, so it does iteration: it produces the unary function "increment (`>`) until the function **f** applied to previous and current values gives a truthy (nonzero) result, then return current value". This means that the argument is incremented until it doesn't divide the input.

```
p\~~|1
 >i

```

Finally, we apply this function to the initial value `1` and print the result with `p`.

# Answer
> 2 votes
## Pyke, 5 bytes

```
1D.f%

```

Try it here!

```
1D.f  - first number after 1 where
    % -  i%input != 0

```

# Answer
> 2 votes
# Beeswax, 19 bytes

```
 >~P~q
{~b"%g<~1fT_

```

Try it online!

Example, using `3` as value

```
                  lstack     gstack  print
           _      [0,0,0]    []            create bee
          T       [0,0,3]                  enter number
         f                   [3]           push top lstack value on gstack
        1         [0,0,1]                  push 1 on lstack
       ~          [0,1,0]                  swap lstack 1st and 2nd
     g<           [0,1,3]                  push gstack 1st on lstack
    %             [0,1,0]                  lstack 1st = 1st % 2nd
   "                                       if lstack 1st > 0 skip next, else don’t skip
  b                                        redirect to upper left
 >                                         redirect to right
  ~               [0,0,1]                  swap lstack 1st and 2nd
   P              [0,0,2]                  increment lstack 1st
    ~             [0,2,0]                  swap lstack 1st and 2nd
     q                                     redirect to lower right
      <                                    redirect to left
     g            [0,2,3]                  push gstack 1st on lstack
    %             [0,2,1]                  lstack 1st = 1st % 2nd
   "                                       lstack 1st > 0 → skip next
 ~                [0,1,2]                  swap lstack 1st and 2nd
{                                    "2"   print lstack 1st to STDOUT
                                           end program

```

# Answer
> 2 votes
# Java 8, 44 + 2 = 46 bytes

```
int m(int x,int y){return x%++y>0?y:m(x,y);}

```

Recursive solution which requires an extra `,1` when calling. Call with `m(x,1)`.

# Answer
> 2 votes
# TI-Basic, 17 bytes

Absolutely genius to use the input as upper bound for for loop?

```
For(I,1,Ans
If not(fPart(Ans/I
End
I

```

# Answer
> 2 votes
# Japt, 5 bytes

```
@uX}a

```

Try it here

# Answer
> 2 votes
# Ruby (C implementation), 26 bytes

```
->n{-(~n...0).min{|x|n%x}}

```

Explanation: `~n` 2s-complement-bitwise-negates n, so it's equivalent for positive n to `-(n+1)`. Let's work through with n=6. We generate a range from -7 to 0, excluding 0, and then find the minimum of that range using a custom comparison function. `min` expects a block that takes two arguments and returns a negative number if the first one is smaller, 0 if they're the same, and 1 if the first one is larger. Here, we're implicitly telling the block to ignore the second argument, so `x` is just the first element in the comparison. The block will return zero when x is the negation of a factor of n: in our n=6 example, `6%-3` is `0`. When it's not, it'll be a negative number: `6%-4` is `-2`.

So as Ruby iterates through the range, it'll do this: -7 is the first candidate for a minimum. Is -6 less than it? It passes -6 (x) and -7 (ignored) into the block, and the block returns 0 (since 6 is a factor of 6), so no. Is -5 less than it? It passes -5 in to the block and it returns a negative number, so yes. So the current candidate is -5. Is -4 less than -5? The block says yes. -3, -2, and -1 all get 0s, so -4 wins.

Finally we negate the result to get 4.

I'm calling this implementation-dependent since the Ruby spec would allow the sorting to be done differently, although my guess is most implementations do it this way.

# Answer
> 2 votes
# Husk, 5 bytes

```
←`-NḊ

```

Try it online! The testing code prints the output for the first 100 terms. Note that the function runs in time proportional to the input value; the `1234567` case takes about 12 seconds on my machine.

# Answer
> 2 votes
# Vyxal `r`, 5 bytes

```
?Ḋ¬)ṅ

```

Try it Online!

Or

# 5 bytes

```
₌ɾKFh

```

Try it Online!

# Answer
> 2 votes
# Fig, \\$10\log\_{256}(96)\approx\\$ 8.231 bytes

```
[FJkxxG@}1

```

Try it online!

```
   k        # Get the factors of
    x       # the input,
  J         # then append
     x      # the input to that (k doesn't include it).
 F          # Filter out anything in that list from:
      G     #   an infinite list
       1    #   starting at 1
        @}  #   incrementing each time.
[           # Get the first item from that.

```

# Answer
> 1 votes
# Befunge, ~~27~~ ~~25~~ 24 bytes

```
&:1>:00p%v
g1+^@.g00_:00

```

Try it online!

**Explanation**

```
&                 Read N from stdin.
 :                Save a duplicate copy.
  1               Push initial test divisor, D.

   >              Main loop starts here.
    :00p          Save a copy of the current D.
        %v        Calculate N modulo D and move down.
         _        If not zero (i.e. N is not divisible by D), then break to the left.
          :       Otherwise continue to the right and prepare another copy of N.
g          00     Retrieve the previously saved D (wrapping to the beginning of the line).
 1+               Increment D.
   ^              Repeat the loop again.

         _        We break out of the loop going left.
      g00         Retrieve the last value of D.
    @.            Write it to stdout and exit.

```

Thanks to Mistah Figgins for saving me a byte.

# Answer
> 1 votes
# Excel VBA, 36 Bytes

Immediates window function; Takes input from cell `A1` and prints to the Immediates window.

```
i=2:While([A1]Mod i=0):i=i+1:Wend:?i

```

# Answer
> 1 votes
# MATL, 6 bytes

```
t:\f1)

```

Try it online!

# Answer
> 1 votes
# Java 7, ~~54~~ ~~51~~ ~~49~~ ~~47~~ 46 bytes

Golfed:

```
int m(int x){int i=1;for(;x%++i<1;);return i;}

```

Ungolfed:

```
int m(int x)
{
    int i = 1;
    for (; x % ++i < 1;);
    return i;
}

```

Nothing fancy... I did try with a `while(1>0)` loop, was 2 bytes longer

# Answer
> 1 votes
# Clojure, 48 Bytes

```
(defn f[n](some #(if(>(mod n %)0)%)(range 1 n)))

```

# Answer
> 1 votes
# PowerShell, 26 bytes

```
for(;!("$args"%++$i)){};$i

```

Try it online!

# Answer
> 1 votes
# Retina, 28 bytes

```
.+
$*11
(1+?)(?!1\1*$).*
$.1

```

Try it online!

Thanks to Martin for 6 bytes!

In the first stage we generate `N + 1` 1s. Then we find the smallest number of ones such that we cannot fit that number evenly into `N` by hard-coding the offset by one that we introduced in the first step. This offsetting is used to allow 1 and 2 to work.

# Answer
> 1 votes
## Japt, 8 bytes

```
U%°V?V:ß

```

This was inspired by Arnauld's solution.

Thanks ETHproductions for golfing this even more!

Try it Online!

# Answer
> 1 votes
# dc, 21 bytes

```
?sn1[1+dlnr%0=b]dsbxp

```

Try it online!

The program works by running through all integers starting with 2 until it finds one that isn't a divisor of the input. The input is kept in register n, and the current number being tested as a divisor/non-divisor is on the stack.

# Answer
> 1 votes
# REXX, 35 bytes

```
arg a
do n=1 until a//n>0
end
say n

```

# Answer
> 1 votes
# AWK, 25 29 27 bytes

```
{for(i=0;!($1%++i););$0=i}1

```

Try it online!

Can save 3 bytes by leaving out the `i=0` but then multi-line input would be incorrect.

As with all `AWK` scripts, the code can be placed in a file or typed in at the command line.

Command Line Usage:

```
awk '{for(i=0;!($1%++i););$0=i}1' <<< inputNumber

```

or place numbers in a FILE each on its own line and do:

```
awk '{for(i=0;!($1%++i););$0=i}1' FILE

```

Two bytes saved by converting to `for` loop, also added TIO link.

# Answer
> 1 votes
# Ruby, 28 bytes

```
->n{(1..n+1).find{|x|n%x>0}}

```

# Answer
> 1 votes
Perl, 25 bytes

```
sub{1 until$_[0]%++$i;$i}

```

# Answer
> 1 votes
# S.I.L.O.S, 49 bytes

```
readIO
lbla
x+1
b=i
b%x
a=1
a-b
if a a
printInt x

```

Try it online!
Fairly simple. I was confused for a little while.

# Answer
> 1 votes
## Labyrinth, 13 bytes

```
+:#
" %#!
?:;

```

Try it online!

### Explanation

To avoid shifting around too many values to keep track of both the input and the current potential divisor, we're storing the latter implicitly as the stack depth by creating copies of the input. The 3x3 block on the left is the main loop. The first iteration doesn't really do anything, but it helps with the overall layout to delay reading the input until later.

```
+   Add top two stack elements. Does nothing on the first two iterations,
    but removes a zero on subsequent iterations.
:   Duplicate. Does nothing on the first iteration, but copies the input
    later on.
#   Push the stack depth. 2 on the first two iterations, increasingly larger
    values later on.
%   Modulo. Gives zero on the first iteration, and acts as the trial division
    later on. If this is positive, the loop is exited.
;   Discard the zero.
:   Duplicate a zero on the first iteration, the input on subsequent iterations,
    increasing the stack depth.
?   Read input on first iteration, push zero later on.

```

Once `%` gives a positive value, we've found a non-divisor of the input. `#` pushes the stack depth once more, `!` prints it. Then the IP hits a dead and turns around. Now `#%` will leave the top of the stack unchanged (and positive), so the IP now enters the 3x3 main loop in counter-clockwise order. `#:+` pushes twice the stack depth but that's irrelevant. `?:;` all together push a single zero so that the `%` now terminates the program due to a division by zero.

# Answer
> 1 votes
# SmileBASIC, 46 bytes

```
INPUT N
FOR I=2TO N+1
IF N MOD I THEN ?I:Q
NEXT

```

I hope that triggering an error to end the program is allowed.

# Answer
> 1 votes
# Emojicode, 74 bytes

```
➡i 10ii➕1ii

```

Try it online!

# Answer
> 1 votes
# C (gcc) 30 bytes

```
i;f(n){for(i=0;n%++i<1;);i=i;}

```

Try it online!

# Answer
> 1 votes
# Forth (gforth), 31 bytes

```
: f 1 begin 1+ 2dup mod until ;

```

Try it online!

### Explanation

```
 1        \ place a 1 on the stack (divisor)
 begin    \ start an indefinite loop
 1+       \ add 1 to the divisor
 2dup     \ duplicate the top 2 stack items (n and divisor)
 mod      \ get n%divisor and place it on top of the stack
 until    \ end the loop when the top of the stack is anything other than 0

```

# Answer
> 1 votes
# \>\<\>, 12 + 3 = 15 bytes

```
:l%?v:
;nll<

```

Try it online!

Takes input via the `-v` flag. Uses the length of the stack as a counter to check the divisibility of the number.

# Answer
> 1 votes
# 05AB1E, 5 bytes

```
∞Ö0k>

```

Bugfix thanks to *@Grimmy* (for `n=1`) at no additional byte-cost, so it can be undeleted again.

Try it online or verify all test cases.

**Explanation:**

```
∞      # Push an infinite positive list: [1,2,3,...]
 Ö     # Check for each whether it evenly divides the (implicit) input-integer
  0k   # Get the first (0-based) index of 0 in this list of 0s/1s
    >  # Increase this index by 1 to make it 1-based
       # (after which this is output implicitly as result)

```

# Answer
> 1 votes
# Perl 6, 13 bytes

```
{+(1...$_%*)}

```

Try it online!

# Answer
> 1 votes
# GolfScript, 15 bytes

```
~:x;1{).x\%!}do

```

Try it online!

```
~:x;              # Store the input in the variable x
    1             # Push 1
     {     !}do   # While it is zero
      )           # Go to the next number
       .x\%       # x mod the current number

```

# Answer
> 1 votes
# Python 3, 39 bytes

```
f=lambda x,i=1:i if x%i!=0else f(x,i+1)

```

Try it online!

This function just returns the second argument if it's a valid answer, and calls itself with an incremented second argument otherwise.

# Answer
> 1 votes
# Canvas, 8 bytes

```
１Ｗ╵╶┌％！｝

```

Try it here!

##### Explanation:

```
1W╵╶┌%!} | Explanation             | Stack Visualization (of first iteration)
---------+-------------------------+-----------------------------------------
1        | Push 1                  | 1
 W     } | Do ...                  | 1
  ╵      |  Increment ToS          | 2
   ╶     |  Push input             | 2, <input>
    ┌    |  Duplicate 2nd from top | 2, <input>, 2
     %!  |  Divides?               | 2, <0/1>
       } | ... while POP is truthy | <output>
         | Print ToS (implicit)    |

```

# Answer
> 1 votes
# Thunno 2, 2 bytes

```
Ƙ%

```

Try it online!

#### Explanation

```
Ƙ%  # Implicit input
Ƙ   # First integer (starting from 1) where the following is truthy:
 %  #  The (implicit) input mod the number
    #  (this is nonzero/truthy iff the input isn't divisible by the number)
    # Implicit output

```

# Answer
> 1 votes
# ARBLE, ~~27~~ 20 bytes

```
(range(2,n+9)&n%x)/z

```

Try it online!

# Answer
> 1 votes
# Alice, 20 bytes

```
/O
\M@/1!w.?h!?%n$K?

```

Try it online!

```
M1!w.?h!?%n$K?O@ # full program
M                # read one argument and put it on the stack
 1!              # save 1 on the tape
   w      n$K    # while loop, until the modulus is not 0
    .            # duplicate the input
     ?h!         # get the number on the tape, increase it and update the tape
        ?%       # pops the input and the number on the tape, push the modulus
             ?O@ # print the last number on the tape, the first number that does not divide the input

```

# Answer
> 1 votes
# Vyxal `r`, 29 bits<sup>v1</sup>, 3.625 bytes

```
?%)ṅ

```

Try it Online!

# Answer
> 1 votes
# Itr, 9 bytes

`#ä2+º%Ì1@`

online interpreter

## Explanation

```
#         ; get an integer N from standard input
 ä2+º     ; push the range from zero to N+1
     %    ; vectorized remainder
      Ì   ; get indices of non-zero elements (zero-indexed)
       1@ ; get 2nd element (mod 0 is always non-zero)

```

# Answer
> 1 votes
# Nibbles, 3 bytes (6 nibbles)

```
/|,~%@

```

Attempt This Online!

I'm always amazed that Nibbles is able to 'fold-from-right' over an infinite list...

```
/|,~%@      # full program
/|,~%@$$    # with implicit variables added
 |          # filter
  .         # 1..
   ~        #    infinity
            # by truthy result of
     @      # input
    %       # modulo
      $     # it;
/           # then, fold from right
       $    # returning left element each time
            # (so: return left-most element)

```

# Answer
> 0 votes
## C 70 bytes

```
 s(int *n){ int f=1;for(f=1;f<(*n);f++){if((*n)%f!=0)return f;}return f;}

```

# Answer
> 0 votes
## Racket 52 bytes

```
(let p((n 2))(cond[(= 0(modulo m n))(p(+ 1 n))][n]))

```

Ungolfed:

```
(define (f m)
  (let loop ((n 2))
    (cond
      [(= 0 (modulo m n))
       (loop (+ 1 n))]
      [else n])))

```

Testing:

```
(f 24)
(f 1234567)
(f 12252240)
(f 232792560)

```

Output:

```
5
2
19
23

```

# Answer
> 0 votes
# bash, 37 bytes

```
(($1%${2-1}))&&echo $2||$0 $1 $[$2+1]

```

Save the program in a file. Run it from the command line with the input number N as an argument:

*scriptname* N

# Answer
> 0 votes
## Batch, 53 bytes

```
@set/ad=%2+1,r=%1%%d
@if %r%==0 %0 %1 %d%
@echo %d%

```

Well I beat Java anyway... Explanation:

* `set /a d = %2 + 1` This takes the second argument and adds 1. Of course, normally there is no second argument, but that's no problem, you just get `+1`, which is still a legal expression.
* `set /a r = %1 %% d` Since `%` is the argument/variable modifier, we need to double it to flag it as the remainder operator.
* `%0 %1 %d%` This is a form of tail recursion. `%0` refers to the batch file itself, `%1` is the original parameter and `%d%` is our loop variable, becoming `%2` in the next iteration.

# Answer
> 0 votes
# DUP, 23 bytes (21 chars)

DUP is a derivative of FALSE, with a similar solution.

```
1[[^^/%0=][1+]#.]⇒a\a

```

Insert the value to be tested between the first `a` and the `\`, like this:

```
1[[^^/%0=][1+]#.]⇒a1234567\a

```

Explanation:

```
                         data
                         stack
1                        [1]                PUSH 1 on data stack
 [              ]⇒a                         define operator a
                   n     [1,n]              PUSH integer n on data stack
                    \    [n,1]              SWAP
                     a                      execute operator a
1[[^^/%0=][1+]#.]⇒a1234567\a
  [      ][  ]#                             while loop: while first block true,
                                                        execute second block
  [               ~1~
   ^                     [n,1,n]            OVER
    ^                    [n,1,n,1]          OVER
     /                   [n,1,n%1,n/1]      MODDIV: computes mod and division
      %                  [n,1,n%1]          POP
       0                 [n,1,n%1,0]        PUSH 0
        =                [n,1,true/false]   n%1 == 0 ?
         ]                                  if false (0), continue at ~2~
                                            if true (-1), execute next block
          [
           1             [n,1,1]            PUSH 1
            +            [n,2]              ADD
             ]#                             return to ~1~
               .  ~2~    [n]                print number to STDOUT
                                            exit operator a, end program

```

Try it out here.

Or clone my DUP GitHub repository for a DUP interpreter written in Julia, with full documentation.

# Answer
> 0 votes
# FALSE, 32 bytes

This FALSE solution is similar to the DUP solution because DUP is a dialect of FALSE with some extra abilities.

```
1[[\$@$@$@$@\/*-0=][1+]#.]a:\a;!

```

In contrast to DUP, FALSE lacks the convenient MOD,DIV operator that computes both the MOD and DIV of two numbers at one time. FALSE only offers an integer division operator `/`. FALSE also does not offer the convenient OVER operator, and using the PICK  operator combo instead costs 3 bytes each. So, the solution above is actually the cheapest way to implement the OVER and MOD operators in FALSE.

Insert the value to be tested between the `:` and the `\`, like this:

```
1[[\$@$@$@$@\/*-0=][1+]#.]a:1234567\a;!

```

Explanation:

```
1[[\$@$@$@$@\/*-0=][1+]#.]a:n\a;!   (n marks the number)

1                                 [1]               PUSH 1 (counter c)
 [                       ]a:                        define function a
                            n     [1,n]             PUSH n
                             \    [n,1]             SWAP
                              a;!                   fetch address of a, execute a
  [               ][ ]#                             while loop while 1st block true,
                                                                execute 2nd block
   \                       ~1~    [1,n]             SWAP
    $                                               DUP
     @                                              ROT
      $@$@$@                      [n,1,n,1,n,1]     DUP,ROT,DUP,ROT,DUP,ROT,SWAP
                                                    (create 2 duplicates of the pair)
            /                     [n,1,n,1,n/1=n]   DIV
             *                    [n,1,n,1*n]       MUL
              -                   [n,1,n-n=0]       SUB
               0                  [n,1,0,0]         PUSH 0
                =                 [n,1,-1]          if 0==0 PUSH true(-1),
                                                    else push false (0)
                                                    if true, execute next block,
                                                    if false, continue at ~2~
                 ]
                  [1+]#           [n,2]             PUSH 1, ADD, (increment c),
                                                    loop back to ~1~

                       .  ~2~     [n,c]             print integer c (top stack value) to STDOUT

```

Try it out here.

# Answer
> 0 votes
# Matlab, 45 Bytes

```
function x=n(a)
x=2;while(~mod(a,x))x=x+1;end

```

# Answer
> 0 votes
# Vitsy, 17 bytes

```
V2v[VvDD1+v{M(x&]

```

The output is the exit code of this program. Assuming that less that `LCM(Range(1,128))` is acceptable range.

Try it online!

### Explanation:

Let `[...]` at the end of the line signify the state of the stack at that line.

```
V2v[VvDD1+v{M(x&]
V                 Capture the input as a final global variable (FGV).
 2v               Save 2 as a temporary variable.
   [            ] Repeat the item in brackets forever.
    V             Push the FGV to the stack.
     v            Dump the temporary variable (TV) to the stack. (call it "x")
      DD          Duplicate twice. The stack looks like [FGV, x, x, x].
        1+        Add one to the top value. [FGV, x, x, x+1]
          v       Capture the top value as the new temp var. (TV = x+1) [FGV, x, x]
           {      Rotate the top to the bottom of the stack. [x, FGV, x]
            M     Pop the top two values, push second-to-top mod top. [x, FGV%x]
             (    Pop the top value. If it is zero, then... [x]
              x   Pop the top value and exit with that exit code. []
               &  Enter a new stack. (Reset the stack).

```

# Answer
> 0 votes
# Java 8, 37 bytes

```
n->{int i=1;while(n%++i<1);return i;}

```

# Answer
> 0 votes
# Scala, 33 bytes

```
(n:Int)=>(1 to n+1)find(n%_>0)get

```

Straightforwardly constructs a `Range` that covers the possible answers, finds the first one that is an answer, and gets it from the `Option`, knowing that it must exist.

# Answer
> 0 votes
# C++ 55 Bytes

```
start: while(n%i>0) {;goto end;} i++; goto start; end:;

```

The while loop checks whether the number(input given by the user) is divisible by i(here the divisor which is continuously increasing).

The entire code is

```
#include<iostream>
using namespace std;
int main(){
int n,i=1;
cout<<"Enter A Number";
cin>>n;
start:
while(n%i>0)
{
cout<<"The lowest integer that does not divide "<<n<<" is "<<i;
goto end;
}
   i++;
goto start;
  end:
return 0;
}

```

# Answer
> 0 votes
**Q/KDB+ 36 Bytes**

```
f:{$[0=(y%x)mod 1;f[x+1;y];x]}
f[1;n]

```

**Description:**
Function f

```
f:{$[0=(y%x)mod 1;f[x+1;y];x]}

```

which consists of a conditional

```
$[0=(y%x)mod 1;f[x+1;y];x]

```

The conditional has 3 statements, each separated by a semi colon.

```
0=(y%x)mod 1  //y divided by x, mod 1 to determine if it is a decimal or not.
f[x+1;y]      //If it is not a decimal, call the function again and increment x.
x             //If it is a decimal, return x (as it doesn't divide n evenly.

```

To call the function:

```
f[1;n]

```

Start at 1 and pass in the value of n.

# Answer
> 0 votes
# GameMaker Language, 58 bytes

```
a=argument0 for(i=1;i<=a;i++){if a mod i return i}return i

```

# Answer
> 0 votes
## Clojure, 90 bytes

Horribly long, but I like how it reads ungolfed.

```
#(apply min(remove(into #{}(filter(fn[m](=(rem % m)0))(range 1(+ % 1))))(range 2(+ % 2))))

```

I probably have a lot of room to golf this given this was a totally naïve attempt at an algorithm.

Ungolfed:

```
(defn smallest [n]
  (let [mults (into #{} (filter (fn [m] (= (rem n m) 0)) (range 1 (+ n 1))))] ; Find multiples, and place in a set for membership lookup
    (apply min ; Find minimum non-multiple
      (remove mults ; Remove multiples from the range 2 to (n+2)
              (range 2 (+ n 2))))))

```

# Answer
> 0 votes
# FALSE, ~~22~~ ~~19~~ 18 bytes

```
1[$$3ø\/*2ø=][1+]#

```

This is a modified version of the other FALSE answer (which is itself a modified version of the DUP answer)

```
1[[\$@$@$@$@\/*-0=][1+]#.]a:\a;!

```

First, of course, we can remove that function definition/call, as well as outputting the number to the stack instead of printing:

```
1[\$@$@$@$@\/*-0=][1+]#

```

`\$@$@$@$@\` is used to create 2 copies of the top 2 values on the stack `{a,b} -> {a,b,a,b,a,b}`. This can be shortened to `1ø1ø1ø1ø` or `$2ø\$2ø\`

```
1[$2ø\$2ø\/*-0=][1+]#

```

For some reason, they are using `a-b==0` rather than just `a==b`...

```
1[$2ø\$2ø\/*=][1+]#

```

And then I messed around some more to save 1 character:

```
1[$$3ø\/*2ø=][1+]#

```

# Answer
> 0 votes
# Julia 0.6, 25 bytes

```
f(n,x=2)=n%x>0?x:f(n,x+1)

```

Try it online!

# Answer
> 0 votes
# Add++, 16 bytes

```
L,RqVAFB]qG$_bUm

```

Try it online!

## How it works

```
L,		; Create a lambda function
		; Example argument: [24]
	R	; Range;            [[1 2 3 4 ... 22 23 24]]
	q	; Set;              [{1 2 3 4 ... 22 23 24}]
	V	; Save and pop;     []
	AFB]q	; Push the factors; [{1 2 3 4 6 8 12 24}]
	G	; Retrieve;         [{1 2 3 4 6 8 12 24} {1 2 3 ... 22 23 24}]
	$_h	; Set difference;   [{5 7 9 ... 22 23 24}]
	bUm	; Minimum;          5

```

# Answer
> 0 votes
# Jelly, 6 bytes

```
R‘ḟÆDḢ

```

Try it online!

**Explanation:**

```
R‘ḟÆDḢ Example input: 5
R      Range 1 to implicit input. [1,2,3,4,5]
 ‘     Increment. [2,3,4,5,6]
  ḟ    Filter out...
   ÆD  The divisors. [2,3,4,6]
     Ḣ Get the first one. 2
       Implicit output

```

# Answer
> 0 votes
# SNOBOL4 (CSNOBOL4), 57 bytes

```
F	F =F + 1
	GT(REMDR(N,F))	:S(RETURN)F(F)
	DEFINE('F(N)')

```

Try it online!

# Answer
> 0 votes
# Funky, 28 bytes

```
n=>fori=1i<n i++ifn%i breaki

```

Obvious solution, but also short enough for me.

Might be the first time I've used break instead of return competitively.

Try it online!

# Answer
> 0 votes
# Pyt, 11 bytes

```
Đ⁺ř|¬ĐŁř*ž↓

```

Explanation:

```
                       Implicitly takes input
Đ                      Duplicates input
 ⁺                     Increments by 1
  ř                    Push [1,2,...,input+1]
   |¬                  Does each of [1,2,...,input+1] not divide the input
     Đ                 Duplicate the array
      Ł                Get the length
       ř               Push [1,2,...,length]
        *              Multiply the top two array elementwise
         ž             Remove all zeroes
          ↓            Get the minimum
                       Implicit print

```

Try it online!

# Answer
> 0 votes
# Powershell, 48 Bytes

```
function f($n){do{$y++;$d=$n%$y}while($d-eq0)$y}

```

Edited to be a function. I'm not really sure how I would golf the "function" bit, but I'm sure there's a way.

# Answer
> 0 votes
## `h` `d`, ~~7~~ 5 bytes

W is doing pretty great, given its lack of a break-out-of-loop instruction!

```
▲²!░╠

```

## Explanation

<pre><code>% Since W doesn't support breaking out
% of loops based on a condition, (design
% preference: I don't like while loops):
% We need some reasoning. We know that
% n and n+1 are always coprime with
% each other, so why not generate a
% range from 1 to n+1?
1+       % Add the inplicit input by 1
     W   % Generate range from 1 to input + 1
         % Keep everything that
         % fullfills the following condition
  bam    % b%a is not falsy (sorry, implicit input
         % isn't working properly)
         % Here, b is the input and a is the current item.

Flag:h % Output the first item of the output
```
</code></pre>

# Answer
> 0 votes
# Whitespace, 58 bytes

```
[S S S T    N
_Push_1][S N
S _Dupe_1][S N
S _Dupe_1][T    N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input][S N
T   _Swap][N
S S N
_Create_Label_LOOP][S S S T N
_Push_1][T  S S S _Add][S T S S T   N
_Copy_0-based_1st_input][S T    S S T   N
_Copy_0-based_1st_n][T  S T T   _Modulo][N
T   S N
_If_0_Jump_to_Label_LOOP][T N
S T _Print_as_integer]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

**Explanation in pseudo-code:**

```
Integer input = STDIN as integer
Integer n = 1
Start LOOP:
  n = n + 1
  If(input modulo n == 0):
    Go to next iteration of LOOP
  Print n as integer to STDOUT
  (Implicitly terminate the program with an error because no exit is defined)

```

**Example program flow (input `24`):**

```
Command  Explanation                   Stack        Heap      STDIN  STDOUT  STDERR

SSSN     Push 1                        [1]
SNS      Duplicate 1                   [1,1]
SNS      Duplicate 1                   [1,1,1]
TNTT     Read STDIN as integer         [1,1]        [{1:24}]  24
TTT      Retrieve from heap #1         [1,24]       [{1:24}]
SNT      Swap top two                  [24,1]       [{1:24}]
NSSN     Create Label LOOP             [24,1]       [{1:24}]
SSSTN     Push 1                       [24,1,1]     [{1:24}]
TSSS      Add top two (1+1)            [24,2]       [{1:24}]
STSSTN    Copy (0-based) 1st from top  [24,2,24]    [{1:24}]
STSSTN    Copy (0-based) 1st from top  [24,2,24,2]  [{1:24}]
TSTT      Modulo (24%2)                [24,2,0]     [{1:24}]
NTSN      If 0: Jump to Label LOOP     [24,2]       [{1:24}]

SSSTN     Push 1                       [24,2,1]     [{1:24}]
TSSS      Add top two (2+1)            [24,3]       [{1:24}]
STSSTN    Copy (0-based) 1st from top  [24,3,24]    [{1:24}]
STSSTN    Copy (0-based) 1st from top  [24,3,24,3]  [{1:24}]
TSTT      Modulo (24%3)                [24,3,0]     [{1:24}]
NTSN      If 0: Jump to Label LOOP     [24,3]       [{1:24}]

SSSTN     Push 1                       [24,3,1]     [{1:24}]
TSSS      Add top two (3+1)            [24,4]       [{1:24}]
STSSTN    Copy (0-based) 1st from top  [24,4,24]    [{1:24}]
STSSTN    Copy (0-based) 1st from top  [24,4,24,4]  [{1:24}]
TSTT      Modulo (24%4)                [24,4,0]     [{1:24}]
NTSN      If 0: Jump to Label LOOP     [24,4]       [{1:24}]

SSSTN     Push 1                       [24,4,1]     [{1:24}]
TSSS      Add top two (4+1)            [24,5]       [{1:24}]
STSSTN    Copy (0-based) 1st from top  [24,5,24]    [{1:24}]
STSSTN    Copy (0-based) 1st from top  [24,5,24,5]  [{1:24}]
TSTT      Modulo (24%5)                [24,5,4]     [{1:24}]
NTSN      If 0: Jump to Label LOOP     [24,5]       [{1:24}]

TNST      Print as integer             [24]         [{1:24}]         5
                                                                             error

```

# Answer
> 0 votes
# Perl 5 `-p`, 15 bytes

```
1until$_%++$\}{

```

Try it online!

# Answer
> 0 votes
# Brachylog v2, 5 bytes

```
f≡ⁿℕ₁

```

Try it online!

```
   ℕ₁    The output is a positive integer
 ≡ⁿ      which is not an element of
f        the input's factors.

```

# Answer
> 0 votes
# Desmos, 34 bytes

Note that this does not work for \\$n\>10000\\$ because of Desmos' maximum list length of 10000.

```
r=[2...n+1]
f(n)=r[\mod(n,r)>0][1]

```

Try it on Desmos!

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


title: Tips for golfing in PHP

text:
# Question
Title: Tips for golfing in PHP
What general tips do you have for golfing in PHP? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to PHP (e.g. "remove comments" is not an answer). Please post one tip per answer.

# Answer
> 24 votes
**Understand how variables and whitespace interact with PHP's language constructs.**

In my (admittedly short) time golfing, I have found that PHP's language constructs (e.g. echo, return, for, while, etc) behave in a less-than-intuitive way when interacting with variables and whitespace.

`echo$v;`, for example, is perfectly valid, as are `return$v;` and other similar constructs. These small reductions in whitespace can lead to a significant cumulative decrease in length.

Keep in mind, though, that variables **before** language constructs require a space after, as in the following example:

```
foreach($a AS$b){}

```

Because `AS` is a language construct, a space is not required before the variable `$b`, but if one were to omit the space *before it*, resulting in `$aAS`, this would be parsed as a variable name and lead to a syntax error.

# Answer
> 23 votes
**Use strings wisely.**

This answer is two-fold. The first part is that when declaring strings, you can utilize PHP's implicit conversion of unknown constants to strings to save space, e.g:

```
@$s=string;

```

The `@` is necessary to override the warnings this will produce. Overall, you end up with a one-character reduction.

is that sometimes, it may be space effective to set a variable to the name of an often used function. Normally, you might have:

```
preg_match(..);preg_match(..);

```

But when golfing, this can be shortened easily to:

```
@$p=preg_match;$p(..);$p(..);

```

With only two instances of "preg\_match", you're only saving a single character, but the more you use a function, the more space you will save.

# Answer
> 13 votes
You don't always need to write out conditional checks. For example, some frameworks use this at the top of their files to block access:

```
<?php defined('BASE_PATH')||die('not allowed');

```

Or in normal functions

```
$value && run_this();

```

instead of

```
if($value) { run_this(); }

```

# Answer
> 10 votes
## Use short array syntax

Since PHP 5.4, arrays can be declared using square brackets (just like JavaScript) instead of the `array()` function:

```
$arr=['foo','bar','baz'];
// instead of
$arr=array('foo','bar','baz');

```

It will save five bytes.

---

But It may cost bytes if you have "holes" in an associative array:

```
$arr=array(,1,,3,,5);
// is one byte shorter than
$arr=[1=>1,3=>3,5=>5];

```

the disadvantage hits a little later if you can fill the holes with "empty" values:

```
// saves two bytes over array()
$arr=[0,1,0,3,0,5];
// but for a larger array
$arr=[0,1,0,3,0,5,0,7,0,9,0,11];
// costs two byte more than
$arr=array(,1,,3,,5,,7,,9,,11);

```

# Answer
> 9 votes
## Use ${0}, ${1}, ${2}, ... instead of $a\[0\], $a\[1\], $a\[2\], ...

Unless you're performing an array manipulation, most references to an array index `$a[$i]` can be replaced with simply `$$i`. This is even true if the index is an integer, as integers are valid variable names in PHP (although literals will require brackets, e.g. `${0}`).

Consider the following implementation of the Rabonowitz Wagon spigot:

```
3.<?for(;$g?$d=0|($a[$g]=$d*$g--/2+($a[$g]?:2)%$g*1e4)/$g--:238<<printf($e?'%04d':'',$e+$d/$g=1e4)^$e=$d%$g;);

```

This can be improved by 6 bytes, simply by replacing both array references `$a[$g]` with `$$g` instead:

```
3.<?for(;$g?$d=0|($$g=$d*$g--/2+($$g?:2)%$g*1e4)/$g--:238<<printf($e?'%04d':'',$e+$d/$g=1e4)^$e=$d%$g;);

```

# Answer
> 6 votes
**Learn a large subset of the library functions**.

PHP's library is pretty huge and provides a ton of convenient functions that can greatly shorten various tasks. You could just search every time you try to do something, but beyond wasting time you might not find anything that matches your particular search. The best way is just to get familiar with the library and memorize function names and what they do.

# Answer
> 6 votes
Running functions inside strings.

Try this:

```
$a='strlen';
echo "This text has {$a('15')} chars";

```

Or try this:

```
//only php>=5.3
$if=function($c,$t,$f){return$c?$t:$f;};
echo <<<HEREDOCS
    Heredocs can{$if(true,' be','not be')} used too and can{$if(<<<BE
{$if(true,1,0)}
BE
,'','not')} be nested
HEREDOCS;
//Expected output: Heredocs can be used too and can be nested

```

This only works with strings using `""` and heredocs (DON'T make confusion with nowdocs).

Using nested functions is only possible inside nested heredocs (or you will run into parse errors)!

# Answer
> 5 votes
# fun with typecasts

* `!!$foo` will turn any truthy value to `true` (or `1` in output), falsy values (0, empty string, empty array) to `false` (or empty output)
This will rarely be needed in code golf, for in most cases where you need a boolean, there is an implicit cast anyway.
* `(int)$foo` can be written as `$foo|0` or `foo^0`, but may need parentheses.
For booleans and strings, `$foo*1` or `+$foo` can be used to cast to int.
* Unlike most other languages, PHP handles strings with numeric values as numbers. So if you have any string that contains a number you have to calculate with, just calculate.
* The other way does *not* work: To multiply any number in a variable with `10`, you could append a zero: `*10` -\> `.0`. But in this case, PHP will take the dot as decimal point and complain. (It´s different though if you have a variable amount of zeroes in a string.)
* To turn an array into a string, use `join` instead of `implode`.
If you don´t need a delimiter, don´t use it: `join($a)` does the same as `join('',$a)`
* Incrementing strings: The most amazing feature imo is that `$s=a;$s++;` produces `$s=b;`. This works with uppercase and lowercase characters. `$s=Z;$s++;` results in `$s=AA;`.
This also works with mixed case: `aZ` to `bA`, `A1` to `A2`, `A9` to `B0` and `z99Z` to `aa00A`.
Decrement does *not* work on strings. (And it does not on `NULL`).
Back in PHP 3, `$n="001";$n++;` produced `$n="002";`. I am a little sad they removed that.

Whatever you golf: **always have the operator precedence table at hand.**

# Answer
> 5 votes
## by any other name ... function aliases

use ...

* `join` instead of `implode`
* `chop` instead of `rtrim` (`chop` in PERL is different!)
* `die` instead of `exit`
* `fputs` instead of `fwrite`
* `is_int` instead of `is_integer` or `is_long`
* `is_real` instead of `is_float` or `is_double`
* `key_exists` instead of `array_key_exists`
* `mysql` instead of `mysql_db_query`

... to name the most important aliases. Take a look at http://php.net/aliases for more.

# Answer
> 5 votes
**looping through strings**

can be done with 26 bytes or with 24 down to 18:

```
foreach(str_split($s)as$c)  # A) 26 - general
for($p=0;a&$c=$s[$p++];)    # B) 24 - general
for($p=0;$c=$s[$p++];)      # C) 22 - if $s has no `0` character
for(;a&$c=$s[$p++];)        # D) 20 - if $p is already NULL or 0 (does NOT work for false)
for(;$c=$s[$p++];)          # E) 18 - both C and D

for(;$o=ord($s[$p++]);)     # F) 23 - work on ASCII codes, if $s has no NULL byte and D
for(;~$c=$s[$p++];)         # G) 19 - if $s has no chr(207) and D

```

---

`$a&$b` does a bitwise AND on the (ascii codes of) the characters in `$a` and `$b`
and results in a string that has the same length as the shorter of `$a` and `$b`.

# Answer
> 4 votes
# Use shorttags

In normal code, it's good practice to use `<?php` and `?>`. However, this is *not* normal code - you are writing a code golf code. Instead of `<?php`, write `<?`. Instead of `<?php echo`, write `<?=`. Don't type `?>` at end - it's completely optional. If you need `?>` for some reason (for example to output text, and it's shorter somehow, or something, don't put a semicolon before it - it's not needed, as `?>` implies semicolon.

Wrong (definitely too long):

```
<?php echo ucfirst(trim(fgets(STDIN)));?>s!

```

Correct:

```
<?=ucfirst(trim(fgets(STDIN)))?>s!

```

# Answer
> 4 votes
# Use ternary operators

```
if(a==2){some code;}else{some other code;}

```

can be abbreviated to this:

```
(a==2?some code:some other code);

```

Shorter, huh?

# Answer
> 4 votes
# array\_flip vs array\_search

use

```
array_flip($array)[$value]

```

instead of

```
array_search($value,$array)

```

to save 1 Byte in arrays where the occurence of each value is unique

# Answer
> 4 votes
# Combining `for` loops

Suppose you have code of the following form:

```
for($pre1; $cond1; $post1) for($pre2; $cond2; $post2) $code;

```

this can generally be re-rolled in the following form:

```
for($pre1; $cond2 • $post2 || $cond1 • $pre2 • $post1; ) $code;

```

where  represents a generic combining operator. This usually results in an byte count reduction, but will likely require some creativity. `$cond2` will need to be written so that it fails the first time through. `$post1` should also fail to execute the first time, although it may be easier to refactor beforehand so that `$post1` is not present.

If you're working with three or more nested loops, you can also combine two first, and then combine that to another, and so on. I find that it has generally been easier to combine from the inside outwards.

---

As an example, consider the following solution to the H-carpet fractal (*97 bytes*):

```
for(;$i<$n=3**$argn;$i+=print"$s\n")for($s=H,$e=1;$e<$n;$e*=3)$s.=str_pad($i/$e%3&1?$s:'',$e).$s;

```

This can be reformulated in the following way:

```
for(;($i+=$e&&print"$s\n")<$n=3**$argn;)for($s=H,$e=1;$e<$n;$e*=3)$s.=str_pad($i/$e%3&1?$s:'',$e).$s;

```

*`$e&&print` prevents `print` on first iteration, and also does not increment `$i`.*

and finally (*93 bytes*):

```
for(;$H>$e*=3or$e=($i+=$e&&print"$s\n")<${$s=H}=3**$argn;)$s.=str_pad($i/$e%3&1?$s:'',$e).$s;

```

*`$H>$e*=3` will fail the first time as both variables are undefined.*

# Answer
> 3 votes
**line breaks**
if the output requires line breaks, use a physical line break (1 byte) instead of `"\n"`
This also gives you a possible benefit to chose between single and double quotes.

# Answer
> 3 votes
### Associative arrays can be merged with the `+` operator.

Instead of:

```
$merged = array_merge($a, $b);

```

Use:

```
$merged = $a + $b;

```

Note the `+` operator works with indexed arrays as well, but probably doesn't do what you want.

# Answer
> 3 votes
**some interesting facts on variable variables**

I just had to share them (even before I verified that at least one of them helps golfing):

* Use letters: `$x=a;$$x=1;$x++;$$x=2;echo"$a,$b";` prints `1,2`
but other arithmetic operations do not work with letters.
* As primo mentioned earlier, you can use pure numbers as variable names:
`$a=1;$$a=5;$a++;$$a=4;${++$a}=3;echo${1},${2},${3};` prints `543`.
* You can not only use `[0-9a-zA-Z_]` for variable names, but EVERY string:
`$x="Hello!";$$x="Goodbye.";echo${"Hello!"};` prints `Goodbye.`.
* But: Everything but `[a-zA-Z_][a-zA-Z_0-9]*` as variable names requires braces for literal use.
* With no variables defined, `$$x=1` sets `${NULL}`, which is the same as `${false}` and `${""}`.
* `$a=1;$$a=5;` does not only set `${1}`, but also `${true}`.
* one more, the weirdest one I´ve found so far: Try `$a=[];$$a=3;echo${[]};`. Yes, it prints `3`!

The reason for most of this: variable names are always evaluated to strings.
<sup>(Thanks @Christoph for pointing out.)</sup>
So, whatever you get when you `print` or `echo` the expression, that´s what you get as variable name.

# Answer
> 3 votes
## PCRE-Related (Regex)

### Functions

If the pattern always matches the subject string (thanks to the comment by @Deadcode), instead of `preg_replace`, you can use `preg_filter` (1 byte shorter).

### Patterns

Sometimes espace sequences are useful, like `\d`, `\w`, `\W`, `\s` or `\S`.

### Examples

Filter non-alphabet characters:

```
preg_replace("/[^a-z]/i", "", $s);
preg_filter("/\W|\d/", "", $s); // 3 bytes shorter

```

# Answer
> 2 votes
**avoid quotes where possible**

PHP implicitly casts unknown words to literal strings.

`$foo=foo;` is the same as `$foo='foo';` (assuming that `foo` is neither a key word or a defined constant): `$foo=echo;` does not work.

BUT: `$p=str_pad;` does; and `$p(ab,3,c)` evaluates to `abc`.

Using string literals without quotes will yield a Notice for `Use of undefined constant`; but that won´t show if you use the default value for `error_reporting` (CLI parameter `-n`).

# Answer
> 2 votes
# array\_merge vs array\_push

```
array_push($a,...$b);

```

is one byte shorter than

```
$a=array_merge($a,$b);

```

Does not work the same with Associative arrays

variable-arg-list PHP \>5.6

# Answer
> 2 votes
# Use boolean operators instead of `strtoupper()` and `strtolower()`

If you're working exclusively with strings consisting of alphabet characters, you can use boolean operators to change them to uppercase or lowercase with fewer keystrokes than PHP's built-in functions.

### Example:

```
// Convert lowercase to uppercase
$s = "g";
echo strtoupper($s);  // Outputs 'G', uses 20 characters
echo~" "&$s;          // Outputs 'G', uses 12 characters

// Convert uppercase to lowercase
$s = "G";
echo strtolower($s);  // Outputs 'g', uses 20 characters
echo$s^" ";           // Outputs 'g', uses 11 characters

// Switch case of each character
$s = "Gg";
echo$s^"  ";          // Outputs 'gG', uses 12 characters

```

Things are a little trickier for strings of arbitrary length, but the `&` and `^` operators will truncate the result to the length of the shorter input string. So for example, if `$W` is a string of spaces at least as long as any input `$s`, then `~$W&$s` is equivalent to `strtoupper($s)`, and `$s|$W^$s` is equivalent to `strtolower($s)` (whereas `$s|$W` by itself will produce a string with additional spaces unless `$s` and `$W` are of equal length).

# Answer
> 2 votes
# Arrow functions in PHP 7.4

PHP 7.4 is on RC2 version now and hopefully will be released in about 2 months. List of new features are here (this page can actually be updated when 7.4 is released). In 7.4, finally PHP has got the arrow functions, so not only function answers can be shorter now, but also passing closures to other functions can be a lot shorter too. Here are a few examples:

**Return input + 1:**

Anonymous function (closure) - 25 bytes - Try it online!

```
function($n){return$n+1;}

```

Arrow function - 12 bytes - Try it online!

```
fn($n)=>$n+1

```

**Multiply items of first input (array of ints) by second input (int):**

Anonymous function (closure) - 72 bytes - Try it online!

```
function($a,$n){return array_map(function($b)use($n){return$b*$n;},$a);}

```

Arrow function - 38 bytes - Try it online!

```
fn($a,$n)=>array_map(fn($b)=>$b*$n,$a)

```

Did you notice that `$n` is accessible in the inner function without a `use $n` statement? Yeah that is one of the arrow function features.

---

As a side note, I could not get arrow functions to work recursively (call the same arrow function inside itself), because we cannot give them a name and storing them as a closure in a variable like `$f` doesn't make `$f` accessible withing itself (sad). So this example **doesn't work** and using `$f` in first line causes a fatal error:

```
$f=fn($n)=>$n?$f($n-1):0;
$f(5); // Causes error: "PHP Notice: Undefined variable: f" + "PHP Fatal error: Uncaught Error: Function name must be a string"

```

But calling an arrow function withing a different arrow function works:

```
$f1=fn($n)=>$n+1;
$f2=fn($n)=>$f1($n-1);
$f1(2) // Returns 3
$f2(2) // Returns 2

```

# Answer
> 1 votes
Regarding file I/O:

Linking to another related question, the answers to which fit here.

# Answer
> 1 votes
### Directly dereference arrays returned from functions.

E.g., instead of this:

```
$a = foo();
echo $a[$n];

```

You can do:

```
echo foo()[$n];

```

This works with methods too:

```
echo $obj->foo()[$n];

```

You can also directly dereference array declarations:

```
echo [1, 2, 3, 4, 5][$n];

```

# Answer
> 1 votes
### Use negative indexes to reference the end of a string

If you need the last character in a string, you can use the array reference method, and provide a negative index:

```
$lastChar = $string[-1];

```

This also works for functions like `substr()`:

```
$lastFour = substr($string, -4);

```

# Answer
> 1 votes
### Use `end()` instead of `array_pop()`

The `end()` function doesn't just move the internal pointer to the end of the array, it also returns the last value. Note of course that it doesn't *remove* that value, so if you don't care what the array contains afterwards, you can use it instead of `array_pop()`.

# Answer
> 1 votes
# double array\_flip vs in\_array vs array\_unique

in this special case a double array\_flip saves 10 Bytes

`($f=array_flip)($k=$f($c)))` remove all double values in the array and I have dropped this `$c=[],` , `|in_array($o,$c)` and replace `array_keys($c)` with `$k`

```
for([,$x,$y]=$argv;a&$o=$y[$i];$i++)
$x[$i]==$o?:$c[$x[$i]]=$o; # if char string 1 not equal char string 2 set key=char1 value=char2
echo strtr($x,($f=array_flip)($k=$f($c)))==$y # boolean replacement string 1 equal to string 2
    ?join($k)." ".join($c) # output for true cases
:0; #Output false cases

```

Online Version

against

```
for($c=[],[,$x,$y]=$argv;a&$o=$y[$i];$i++)
  $x[$i]==$o|in_array($o,$c)?:$c[$x[$i]]=$o; # if char string 1 not equal char string 2 set key=char1 value=char2
echo strtr($x,$c)==$y # boolean replacement string 1 equal to string 2
  ?join(array_keys($c))." ".join($c) # output for true cases
  :0; #Output false cases

```

Online version

against array\_unique it saves 2 Bytes

```
for([,$x,$y]=$argv;a&$o=$y[$i];$i++)
  $x[$i]==$o?:$c[$x[$i]]=$o; # if char string 1 not equal char string 2 set key=char1 value=char2
echo strtr($x,array_unique($c))==$y # boolean replacement string 1 equal to string 2
  ?join(array_keys($c))." ".join($c) # output for true cases
  :0; #Output false cases

```

Online Version

After finding a bug in this program and replacement `$x[$i]==$o?:$c[$x[$i]]=$o` to `($p=$x[$i])==$o?:$k[$c[$p]=$o]=$p` the double array\_flip was not necessary longer

# Answer
> 1 votes
## Return two copies of an expression

If you want to get two copies of the result of an expression, you can use this:

```
$v.$v=expr

```

But it won't be shorter than the more straightforward `($v=expr).$v` if you need to append more things to the result.

For 4 copies:

```
$v.$v.=$v=expr

```

You cannot use it to get 3 copies.

# Answer
> 1 votes
**intersecting strings**

Have you ever used
`join("DELIMITER",str_split($s))` (31 bytes) or even
`preg_replace(".","DELIMITER",$s)` (32 bytes)
?

There´s a builtin for that:

Try `chunk_split($s,1,"DELIMITER")` (29 bytes).

---

If you omit the third parameter, `chunk_split` will use `\r\n`; that can save you 7 or 8 bytes.

But beware: `chunk_split` also appends the delimiter to the string,
so you may not get exactly what you want.

(If you don´t provide the chunk length, it will use 76. Rather unusual for code golf, but who knows.)

# Answer
> 1 votes
# Removing characters in a string

```
join(explode(" ",$string));

```

saves 1 character compared to

```
str_replace(" ","",$string);

```

# Answer
> 1 votes
# str\_repeat

In some cases you have a input of characters and you should output them repeated with an input greater zero for each characters.

```
for(;--$z?:($c=$argn[$i++]).$z=$argn[$i++];)echo$c;

```

(52 bytes) is shorter than

```
for(;~$c=$argn[$i++];)echo str_repeat($c,$argn[$i++]);

```

or

```
for(;~$c=$argn[$i++];)echo str_pad($c,$argn[$i++],$c);

```

(54 bytes each)

## How it works for example input `a1b2c1`

`$z` is not set (implicit `NULL`), so `--$z` does nothing and is falsy;

`$c="a"`, `$z="1"` and `$i=2` -\> `$c.$z="a1"` is truthy -\> output `"a"`

`--$z=0`; so we set `$c="b"`, `$z="2"` (and `$i=4`) -\> `$c.$z="b2"` is truthy -\> output `"ab"`

`--$z=1` -\> output `"abb"`

`--$z=0`; so we set `$c="c"` and `$z=1` `$c.$z="c1"` is true output `"abbc"`

`--$z=0` so `$c=""` and `$z=""` -\> `$c.$z=""` is falsy -\> loop breaks

# Answer
> 1 votes
# unset() vs INF

In a case search for a minimum in an array you can use instead of

```
unset($var[$k]);

$var[$k]=INF;

```

to save 3 Bytes

# Answer
> 0 votes
**use deprecated functions**
If you can use POSIX instead of PERL regex without wasting more than 5 bytes on the expression, use `ereg` or `eregi` instead of `preg_match`, `split` or `spliti` instead of preg\_split.
`split` Can also be used as a synonym for `explode` for most delimiters.

These functions are marked deprecated and will throw `E_DEPRECATED` notices, but (cannot find the source now) I think I have read that warnings and notices are ok.

# Answer
> 0 votes
### Use short append syntax to add elements to the end of an array.

Instead of keeping track of the number of elements:

```
$array[++$i] = $value;

```

Or using the explicit push function:

```
array_push($array, $value);

```

You can use the implicit push feature:

```
$array[] = $value;

```

# Answer
> 0 votes
### JSON encode static array definitions

JSON encoding is one byte shorter per element than native PHP encoding for associative arrays. Of course, then you have to quote the resulting string (an additional two chars) and call `json_decode()` on that string (an additional 13 chars.) So, if you have a static associative array with more than 15 elements, try JSON encoding it. Note this probably won't work if you can use the "unquoted string literals" trick in your PHP array definition.

Instead of:

```
$array = [...];

```

Use:

```
$array = json_decode('...');

```

# Answer
> 0 votes
# Switches base on arrays or strings

A little collection which can save Bytes for different conditions

Switch a function through an array

```
<?=(bc.[sub,add,mul,pow][($x=$argn)&3])($x,$x);

```

Make different Math operations

```
<?=[0,($x=$argn)+$x,$x*$x,$x**$x][$x&3];

```

Ternary Operator to switch a function

```
echo(strto.(rand()&1?low:upp).er)($c);

```

Using the Keys in an array as conditions

```
echo[ctype_alpha($s=dechex($argn))=>"Only letters",ctype_digit($s)=>"Only numbers",Mix][1];

```

special on strings but only not in all cases you must use a function and `trim` will do nothing

```
($bool?trim:strtolower)($string)

```

character switch

```
"char"[$x%4]

```

character only in zero cases

```
"c"[$x%2]

```

# Answer
> 0 votes
I didn't see it listed so when using a list and explode you can use a number as the delimiter ( assuming its not in the string of course ). This lets you get rid of the quotes.

If there is backslash before the delimiter then it has to be `8` or `9` so it doesn't get confused with octal ( such as `\0` )

So instead of:

```
explode(",", "one,two,buckle,my,shoe")

```

You can do this

```
explode(1, "one1two1buckle1my1shoe")

```

Saving 2 bytes for the quotes.

As I mentioned for backslashes

```
explode(",", "/ \,| .. |,\ /");

```

Use `8` or `9`

```
explode(8, "/ \8| .. |8\ /");  // so you get \8 instead of \0 etc..

```

# Answer
> 0 votes
# seek potential in combining several expressions to one

It´s easy to see that `A?B:C;` is shorter than `if(A)B;else C;`
`A&&B` is shorter than `if(A)B;` and `A||B;` is shorter than `if(!A)B;`

But how can `if(A){B;C;}else{D;E;}` be golfed?

Assume that `B` returns something truthy and `D` something falsy:

```
if(A){B; C;}else{B; C;}  # 21 bytes
A?    B&&C  :    B||C;   # 12 bytes

```

another one:

```
if(A){$b=123;$c="hello";} # 25 bytes
A&&$b=123+!$c="hello":    # 22 bytes
A&&$c="hello".!$b=123;    # also 22 bytes

```

`$c="hello` is truthy, so `!$c` is `false`. `+` casts to int; so we add `0` to `123`.
`$b=123` is truthy, so `!$b` is `false`. `.` casts to string, and that´s empty for `false`.

I even had a case today where appending digits to the string didn´t make a difference.
(See line 5 of the breakdown.)

more examples:

```
for(;;$a++,print$x);
for(;;$a+=print$x);

```

`print` always returns true, so its return value can be added to `$a` instead of incrementing `$a` separately.

```
$a=1,$b=0
$a=!$b=0

if(X){$a=123;$b=0;}
X&&$a=123+$b=0;     # useful if you need $b to be and int (for printing)
X&&$b=!$a=123;

if(X){$a=123;$b=1;}
X&&$b=!!$a=123;
X&&$a=123*$b=1;

```

## advanced: combining nested loops

takes a new level to combining expressions. There is no general solution or approach; and it doesn´t always make the code shorter. Good chances are when the outer loop has no body except the inner loop; imagine shifting through a 2D array or sorting one.

Try

```
for($a=1;$a<20;$a+=print"\n")for($b=$a;$b++<20;)echo$a*$b,"\t";

```

61 bytes (counting the control characters as one each)
that loop `$a` from `1` to `19`, `$b` from `$a+1` to `20`
and print the products, breaking the line when `$a` increments.

Ok, one simple two-byte saving is

```
for($a=1;20>$b=$a;$a+=print"\n")for(;$b++<20;)echo$a*$b,"\t";

```

Combining the two loops to one saves another two bytes:

```
for($a=$b=1;$b++<20||21>$b=1+$a+=print"\n";)echo$a*$b,"\t";

```

And you can save two more bytes with a leading linebreak instead of a trailing one (this often saves a byte or two):

```
for($b=20;$b++<20||21>$b=1+$a+=print"\n";)echo$a*$b,"\t";

```

This is a pretty easy and rewarding example; so don´t be upset if your first attempts fail on saving bytes. It may take a while until you get an eye for it.

Ok, `for(;20>$b=++$a;print"\n")for(;$b++<20;)echo$a*$b,"\t";` is golfier; and in PHP 7, you can even avoid trailing tabs without any costs: `for(;20>$b=++$a;)for(;$b++<20;)echo$a*$b,"\n\t"[$b<20];`

But imagine you have to loop `$a` from somewhere else but `1`, like through ascii codes.

I may one day come up with an example that makes more sense. No promises on these premises though.

# Answer
> 0 votes
When using `array_values()` to re-index an array with numeric keys, from PHP7.4 you can use a technique that I call splatpacking (**see link for further details and a demonstration**).

You use the "splat/spread" operator to "unpack" the array, then immediately "repack" the elements into an empty array. Though not designed for this purpose, the result is the same -- in that limited scenario.

Technique using `$a` representing an array:

```
array_values($a)  // 14 characters (not counting $a)

```

becomes

```
[...$a]  // 5 characters (not counting $a)

```

# Answer
> 0 votes
## Little-known tricks with increment/decrement

```
$x = 'a';
echo ++$x; // Outputs "b"

$x = 'z';
echo ++$x; // Outputs "aa"

```

And many more at the following RFC, showing they will be removed/normalized in PHP 8.3

https://wiki.php.net/rfc/saner-inc-dec-operators

---
Tags: code-golf, tips, php
---


title: Am I a Cullen Number?

text:
# Question
Title: Am I a Cullen Number?
A Cullen Number is any number that is contained in the sequence generated using the formula:

C(n) = (n\*2^n)+1.

## Your Task:

Write a program or function that receives an input and outputs a truthy/falsy value based on whether the input is a Cullen Number.

## Input:

A non-negative integer between 0 and 10^9 (inclusive).

## Output:

A truthy/falsy value that indicates whether the input is a Cullen Number.

## Test Cases:

```
Input:    Output:
1   --->  truthy
3   --->  truthy
5   --->  falsy
9   --->  truthy
12  --->  falsy
25  --->  truthy

```

## Scoring:

This is , so the lowest score in bytes wins.

# Answer
> 7 votes
# **Pyth, ~~6~~ 5 bytes**

```
/mh.<

```

try it online

# Answer
> 18 votes
## x86\_64 machine code (System V ABI), 28 27 bytes

-1 byte thanks to @Cody Gray, thanks!

A constant-time algorithm!

```
_cullen:
   0:   0f bd cf    bsrl    %edi, %ecx
   3:   0f bd c1    bsrl    %ecx, %eax
   6:   89 ca       movl    %ecx, %edx
   8:   29 c2       subl    %eax, %edx
   a:   0f bd c2    bsrl    %edx, %eax
   d:   29 c1       subl    %eax, %ecx
   f:   d3 e1       shll    %cl, %ecx
  11:   ff c1       incl    %ecx
  13:   31 c0       xorl    %eax, %eax
  15:   39 f9       cmpl    %edi, %ecx
  17:   0f 94 c0    sete    %al
  1a:   c3          retq

```

**Explanation:**

Let *y* an integer and `x=y*2^y + 1`. Taking logs, we have `y + log2(y) = log2(x-1)`, thus `y=log2(x-1)-log2(y)`. Plugging back the value of y, we get `y=log2(x-1)-log2(log2(x-1)-log2(y))`. Doing this one more time, we obtain: `y=log2(x-1)-log2[log2(x-1)-log2(log2(x-1)-log2(log2(x-1)-log2(y)))]`.

Let us remove the last terms (of the order of `log2(log2(log2(log2(x))))`, this should be safe!), and assume that `x-1≈x`, we obtain: `y≈log2(x)-log2[log2(x)-log2(log2(x))]`

Now, letting `f(n) = floor(log2(n))`, it can be verified manually that `y` can be exactly retrieved by: `y=f(x)-f[f(x)-f(f(x))]`, for *y \< 26*, and thus *x ⩽ 10^9*, as specified by the challenge(1).

The algorithm then simply consists of computing *y* given *x*, and verify that *x == y\*2^y + 1*. The trick is that `f(n)` can simply be implemented as the `bsr` instruction (bit-scan reverse), which returns the index of the first 1-bit in *n*, and `y*2^y` as `y << y`.

**Detailed code:**

```
_cullen:                                 ; int cullen(int x) {
   0:   0f bd cf    bsrl    %edi, %ecx   ;  int fx = f(x);
   3:   0f bd c1    bsrl    %ecx, %eax   ;  int ffx = f(f(x));
   6:   89 ca       movl    %ecx, %edx
   8:   29 c2       subl    %eax, %edx   ;  int a = fx - ffx;
   a:   0f bd c2    bsrl    %edx, %eax   ;  int ffxffx = f(a);
   d:   29 c1       subl    %eax, %ecx   ;  int y = fx - ffxffx;
   f:   d3 e1       shll    %cl, %ecx    ;  int x_ = y<<y;
  11:   ff c1       incl    %ecx         ;  x_++;
  13:   31 c0       xorl    %eax, %eax
  15:   39 f9       cmpl    %edi, %ecx
  17:   0f 94 c0    sete    %al
  1a:   c3          retq                 ;  return (x_ == x);
                                         ; }

```

(1)In fact, this equality seems to hold for values of *y* up to 50000.

# Answer
> 7 votes
# Jelly, ~~7~~ 6 bytes

```
Ḷæ«`i’

```

Try it online!

Takes input as a command-line argument. If given a Cullen number C(*n*), outputs *n*+1 (which is truthy in Jelly, being an nonzero integer; note that we have *n*≥0 because the input is an integer, and Cullen numbers with negative *n* are never integers). If given a non-Cullen number, returns 0, which is falsey in Jelly.

## Explanation

```
Ḷæ«`i’
Ḷ        Form a range from 0 to (the input minus 1)
 æ«      Left-shift each element in the range by
   `       itself
    i’   Look for (the input minus 1) in the resulting array

```

Basically, form an array of Cullen numbers minus one, then look for the input minus one in it. If the input is a Cullen number, we'll find it, otherwise we won't. Note that the array is necessarily long enough to reach to the input, because C(*n*) is always greater than *n*.

# Answer
> 7 votes
## JavaScript (ES6), ~~37~~ 35 bytes

*Saved 2 bytes thanks to Neil*

```
f=(n,k,x=k<<k^1)=>x<n?f(n,-~k):x==n

```

### Demo

```
f=(n,k,x=k<<k^1)=>x<n?f(n,-~k):x==n

console.log(JSON.stringify([...Array(1000).keys()].filter(n => f(n))))
```

# Answer
> 5 votes
## Haskell, 28 bytes

```
f n=or[x*2^x+1==n|x<-[0..n]]

```

Try it online!

# Answer
> 3 votes
# , ~~53~~ ~~51~~ 46 bytes

```
pryr::f(x%in%lapply(0:x,function(y)(y*2^y+1)))

```

Anonymous function. Checks if `x` is generated in the sequence C(n) for n in \[0,x\].

3 bytes golfed by Giuseppe.

Try it online!

# Answer
> 3 votes
# Ohm, 8 bytes

```
@Dº*≥Dlε

```

Try it online!

```
           Implicit input
@          Range [1,...,Input]
 D         Duplicate
  º        2^n each element
   *       Multiply those two array
    ≥      Increment everything (now I have an array of all Cullen Numbers)
     Dl    Push array length (= get input again, can't get again implicitly or using a function because it would be a string so I'd waste a byte again)
       ε   Is input in array?

```

# Answer
> 3 votes
# PHP, 43 bytes

```
for(;$argn>$c=1+2**$n*$n++;);echo$argn==$c;

```

Try it online!

# Answer
> 3 votes
# 05AB1E, 7 bytes

```
ÝDo*¹<å

```

Try it online!

**Explanation:**

```
ÝDo*¹<å Example input: 9. Stack: [9]
Ý       Range 0-input. Stack: [[0,1,2,3,4,5,6,7,8,9]]
 D      Duplicate. Stack: [[0,1,2,3,4,5,6,7,8,9],[0,1,2,3,4,5,6,7,8,9]]
  o     2** each item in the list. Stack: [[0,1,2,3,4,5,6,7,8,9], [1,2,4,8,16,32,64,128,256,512]]
   *    Multiply the two lists. Stack: [[0, 2, 8, 24, 64, 160, 384, 896, 2048, 4608]]
    ¹   Push input again. Stack: [[0, 2, 8, 24, 64, 160, 384, 896, 2048, 4608],9]
     <  Decrement. Stack: [[0, 2, 8, 24, 64, 160, 384, 896, 2048, 4608],8]
      å Is the first item of the stack in the second item? Stack: [1]
        Implicit print.

```

# Answer
> 3 votes
## C, C++, Java, C#, D : 70 bytes

Due to the similarities between all these languages, this code works for each

```
int c(int n){for(int i=0;i<30;++i)if((1<<i)*i+1==n)return 1;return 0;}

```

# Answer
> 2 votes
# Python 2, 36 bytes

```
f=lambda n,i=0:i<<i!=n-1and f(n,i+1)

```

Try it online!

Outputs by not crashing / crashing, as *currently* allowed by this meta concensus.

---

# Python 2, 42 bytes

```
i=0
n=input()-1
while i<<i<n:i+=1
i<<i>n<c

```

Try it online!

Outputs via exit code

# Answer
> 2 votes
# Python, 40 bytes

```
lambda n:any(x<<x==n-1for x in range(n))

```

Try it online!

# Answer
> 2 votes
# , 26 bytes

```
a=0:26;scan()%in%(1+a*2^a)

```

Try it online!

A slightly different approach than the other R answer; reads from `stdin` and since the input is guaranteed to be between 0 and 10^9, we just have to check `n` between 0 and 26.

# Answer
> 2 votes
# APL (Dyalog), 9 bytes

To cover the case of *n* = 1, it requires `⎕IO←0` which is default on many systems.

```
⊢∊1+⍳×2*⍳

```

Try it online!

\[is\] *n* (the argument)

a member of

`1` one

`+` plus

the **i**ntegers 0 … (*n*-1)

`×` times

`2` two

`*` to the power of

the **i**ntegers 0 … (*n*-1)

# Answer
> 2 votes
# Python 2, 32 bytes

```
[n<<n|1for n in range(26)].count

```

Try it online!

Creates the list of Cullen numbers up to `10^9`, then counts how many times the input appears in it. Thanks to Vincent for pointing out `n<<n|1` instead of `(n<<n)+1`, saving 2 bytes.

# Answer
> 2 votes
# TI-BASIC, 17 bytes

```
max(Ans=seq(X2^X+1,X,0,25

```

**Explanation**

```
seq(X2^X+1,X,0,25 Generate a list of Cullen numbers in the range
Ans=              Compare the input to each element in the list, returning a list of 0 or 1
max(              Take the maximum of the list, which is 1 if any element matched

```

# Answer
> 2 votes
# D, 65 bytes

This is a port of @HatsuPointerKun's algorithm to D (the original was already D code, but this is with D-specific tricks)

```
T c(T)(T n){for(T i;i<30;++i)if((1<<i)*i+1==n)return 1;return 0;}

```

# How? (D specific tricks)

D's template system is shorter than C++'s, and can infer types. And D also initializes its variables to the default upon declaration.

# Answer
> 2 votes
# Nibbles, 5.5 bytes (11 nibbles)

```
?.`,$+~*^2

```

Returns 1-based index in list of Cullen numbers (truthy), or zero (falsy) if not a Cullen number.

```
?.`,$+~*^2      # full function
?.`,$+~*^2$$$   # (with implicit arguments shown):
 .              # map over
  `,$           # 0..input-1
                # with function:
     +          #   add
      ~         #   1 (default)
                #   to
        ^2      #   2 to the power of
          $     #   input
       *   $    #   multiplied by input
?           $   # and get the index of the input in this
                # (or zero if not found)

```

# Answer
> 2 votes
# Julia 1.0, 23 bytes

```
~n=n∈0:n.|>x->x*2^x+1

```

Try it online!

# Answer
> 1 votes
# Mathematica, 30 bytes

```
MemberQ[(r=Range@#-1)2^r+1,#]&

```

Pure function taking a nonnegative integer as input and returning `True` or `False`. If the input is `n`, then `(r=Range@#-1)` sets the variable `r` to be `{0, 1, ..., n-1}`, and then `r2^r+1` vectorially computes the first `n` Cullen numbers. `MemberQ[...,#]` then checks whether `n` is an element of the list.

# Answer
> 1 votes
# Mathematica, 32 bytes

```
!Table[x*2^x+1,{x,0,#}]~FreeQ~#&

```

# Answer
> 1 votes
# Excel VBA, 45 Bytes

Anonymous VBE immediate window function that takes input from cell `[A1]` and ouputs to the VBE immediate window

*Must be run in a clean module or have values for i,j be reset to default value of 0 between runs*

```
While j<[A1]:j=(i*2 ^ i)+1:i=i+1:Wend:?j=[A1]

```

### Input / Output

I/O as seen in VBE immediate window

```
[A1]=25
While j<[A1]:j=(i*2 ^ i)+1:i=i+1:Wend:?j=[A1]
True

[A1]=1: i=0:j=0 ''# clearing module values
While j<[A1]:j=(i*2 ^ i)+1:i=i+1:Wend:?j=[A1]
True

[A1]=5: i=0:j=0 ''# clearing module values
While j<[A1]:j=(i*2 ^ i)+1:i=i+1:Wend:?j=[A1]
False

```

# Answer
> 1 votes
## Swi-Prolog, 69 bytes

`f(X)` succeeds if it can find a value I where X = I\*2^I+1. The range hint stops it running out of stack space, but it's enough for the range of Cullen numbers up to 10^9 in the question spec.

```
:-use_module(library(clpfd)).
f(X):-I in 0..30,X#=I*2^I+1,label([I]).

```

e.g.

```
f(838860801).
true

```

# Answer
> 1 votes
# cQuents, 9 bytes

```
$0?1+$2^$

```

Try it online!

## Explanation

```
$0           n is 0-indexed
  ?          Mode query. Given input n, output true/false for if n is in the sequence.
   1+$2^$    Each item in the sequence equals `1+index*2^index`

```

# Answer
> 1 votes
# Arturo, 29 bytes

```
$=>[in?&map 0..25'n->1+n*2^n]

```

Try it

# Answer
> 1 votes
# Japt `-d`, 7 bytes

```
ÑpU ¶NÉ

```

Try it

```
ÑpU ¶NÉ     :Implicit map of each U in the range [0,input)
Ñ           :Multiply by 2
 pU         :Raised to the power of U
    ¶       :Is equal to
     N      :Array of all inputs
      É     :Minus 1
            :Implicit output of whether or not any U returns true

```

# Answer
> 1 votes
# Raku, 30 bytes

```
{$_∈({1+$++*2**$++}...*>$_)}

```

Try it online!

The parenthesized expression is a list of generated Cullen numbers, taken up to the point where a number is greater than the input argument (`* > $_`). Then we just check that the input argument is a member of that list ().

# Answer
> 1 votes
# Vyxal, 6 bytes

```
ʀ:E*›c

```

Try it Online!

## Explained

```
ʀ:E*›c
ʀ:     # push 2 copies of the range [0, input]
  E    # 2 ** x for x in ^
   *   # vectorised multiply with the other copy
    ›  # + 1
     c # contains the input?

```

# Answer
> 1 votes
# Thunno `D`, \\$ 11 \log\_{256}(96) \approx \\$ 9.05 bytes

```
RD2@z*s1-Aq

```

Attempt This Online!

#### Explanation

```
RD2@z*s1-Aq  # Implicit input
RD           # Push range(input) and duplicate
  2@         # Pop one copy and push 2 ** each
    z*       # Multiply elementwise
      s1-    # Push the input decremented
         Aq  # Is this in the list?

```

# Answer
> 1 votes
# Pyt, 8 bytes

```
Đ0⇹ŘĐ«⁺∈

```

Try it online!

```
Đ             implicit input; Đuplicate
 0⇹Ř          Řangify from 0 to n
    Đ         Đuplicate
     «        bitshift left
      ⁺       increment
       ∈      is input in list of Cullen numbers?; implicit print

```

# Answer
> 0 votes
# QBIC, 24 bytes

```
[0,:|~a*(2^a)+1=b|_Xq}?0

```

## Explanation

```
[0,:|           FOR a = 0 to b (input from cmd line)
~a*(2^a)+1=b    IF calculating this a results in b
|_Xq            THEN quit, printing 1
}               NEXT a
?0              We haven't quit early, so print 0 and end.

```

# Answer
> 0 votes
# , 19 bytes

```
{&1=x-{x**/x#2}'!x}

```

Try it online. Truthy is an array with a number in it: `,3` or `,0` et cetera. Falsey is an empty array: `()` or `!0` depending on your interpreter.

# Answer
> 0 votes
# Java (OpenJDK 8), 56 bytes

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

```

Try it online!

# Answer
> 0 votes
# Pari/GP, 25 bytes

```
n->!prod(i=0,n,n-i*2^i-1)

```

Try it online!

# Answer
> 0 votes
# Thunno 2 `-c`, 5 bytes

```
ĖıỴ;Ƈ

```

Try it online!

Port of user62131's Jelly answer.

## Thunno 2, 6 bytes

```
ĖDO×⁺Ƈ

```

Try it online!

#### Explanation

```
ĖıỴ;Ƈ  # Implicit input
       # Decrement the input
Ė      # Push [0..input-1]
  Ỵ    # Left bit-shift each
 ı ;   # number by itself
    Ƈ  # Is (input - 1)
       # in this list?
       # Implicit output

```

```
ĖDO×⁺Ƈ  # Implicit input
Ė       # Push [0..input]
 D      # Duplicate it
  O     # Push 2 ** that
   ×    # Multiply together
    ⁺   # Increment each
     Ƈ  # Is the input
        # in this list?
        # Implicit output

```

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