text:
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 code-golf, 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 = '
' + c.body.replace(OVERRIDE_REG, '') + '
';
    });

    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 (/ 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;
}

<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

I turned the sample output string into a vector of numbers, and realized that if you format it 24 columns across, it's extremely repetitive, except for the odd deviation.

That makes sense, 24 is 0 mod 2, 3, and 4, so the only differences would be in columns where the numbers are >4. It's even more repetitive at width 120.

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.

Very interesting way to loop without using For, While, etc

I learned it from this site! I'm definitely enjoying learning more about Mathematica by being here (can I justify that on my timesheet...?).

That does not look like mathematica O_o

don't let the lack of capital letters and brackets fool ya ;)

I was going to apply this to this challenge, but //.will only try the replacements 65536 times. FYI

whoa! I wonder if there's a $-setting that can override that. But you're right—for example, my algorithm gives the wrong answer on input 65538!.

What does "until it stops mattering" mean?

It repeatedly applies the rule to the expression until the expression no longer changes. For example, 240//.x/;EvenQ@x:>x/2 will repeatedly halve 240 to 120, 60, 30, 15 until the rule doesn't apply any more, and then stop, returning 15.

Actually only 28436 digits.

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));

Exactly what I got. I'd be surprised if anything shorter is possible

@ETHproductions On second thought, there's a shorter one. :-)

Um. That's... uh... wow.

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.

Saw the problem, made this answer, came here to post it, found yours. Well done!

I wrote this and felt awesome about myself: .V1In%Qb0bB
Saw your answer, and not feeling so awesome anymore.

@JohnRed Lol, I think you just need to familiarize yourself with the built-ins in Pyth.

Hexagony, 12 bytes
\\)?}'@{!%.}

Embiggened:
   \ \ )
  ? } ' @
 { ! % . }
  . . . .
   . . .

Try it online!

That's a very impressive score for Hexagony, nice work!

Python, 43 36 35 bytes
f=lambda n,d=2:d*(n%d>0)or f(n,d+1)

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.

Nice, just wanted to suggest using which.min, but then I saw the edit and it seems match does a similar job.

Also, nice trick using T, saving the need to define it before the while loop.

@JarkoDubbeldam Thanks! I can't find a way for the vectorized approach to be shorter than the while approach, which is fine as it's very memory-intensive for large N. The T trick is one of those treats which is great for golfing but absolutely horrible for actual programming. (And of course you can use F too when you need a 0.)

You may save two bytes by using 0:i+1 instead of 1:(i+1) although I am not sure how it plays with the %% operator.

@antoine-sac Unfortunately, %% takes precedence over +, so parens are still necessary: (0:i+1), with the same number of bytes as 1:(i+1). I actually had the former originally, but changed it to the latter as it's easier to read.

Haskell, 26 bytes
f n=until((>0).mod n)(+1)1

Everyone forgets about until!

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.

Never thought about doing that, that's neat!

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.

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

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

Nice, I was wondering how you'd do this iteratively in 05AB1E.

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);}

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.)

Damn you Jelly! Pyth beats you today! :D

ASCII-only: 2%@1#

C#, 39 37 bytes
n=>{int i=0;while(n%++i<1);return i;}

Saved two bytes thanks to Martin!

I like while(!(n%++i)); better but of course, this is code golf and 1 byte is 1 byte.

Does that work? I didn't know that the 0 evaluated to false automatically

Ah, I tried it in C++, yeah it doesn't work with C#.

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!

@(n)find(mod(n,1:n+1),1) is shorter, isn't it?

it is indeed, thanks!

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.

@Zgarb missed that part, initial increment by 2 fixes the problem.

Nice! I always forget that 05ab1e has a divisor function :)

I know this wasn't possible yet in the legacy version of 05AB1E, but it can be -1 now by using ∞ instead of ÌL. :) I've also just posted an alternative 5-byter.

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.

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

I don't know Jelly, but could you save a byte by increasing N before you generate the range?

@Emigna I don't know Jelly either ;) I don't see how: incrementing it earlier also makes the modulo test against N+1, or increaes the remainders [1, 1, 1, 1, 5, ...].

Ah, I see. I thought it might be possible to do N%range(1,N+1), but if it increases the N in both instances that's no good.

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).

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.

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 .. *
}

13 bytes

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

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

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!

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.

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;

IIRC, the <? doesn't have to be part of your byte count (because PHP has a command-line mode that doesn't require it).

The old trick: compare against <1 instead of ==0.

Dang. I reached to for(;!($argv[1]%$i);$i++);echo$i;. Yours is the natural evolution of mine. This has my upvote!

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]

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));
    }
}

I believe you have your ternary operator backwards. x%i?i:f(x,i+1) will call f(x,i+1) when x is NOT divisible by i instead of when it is.

@RobertBenson When x is divisible by i, x%i produces the value zero, which is interpreted as false by C, so f(x,i+1) gets called. Thus, the recursion happens as long as x is divisible by i, just as it should. But I agree, this ternary expression is mind-screwing: I wrote it the wrong way round at the first try myself...

That's what I get for looking at these things while I'm trying to dig through FORTRAN code at work. Also... I might have looked at a different question just before looking at your answer... yeah... I'll use that as my excuse. :)  Nice work.

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.

I2/L/);?%<@O for a couple of bytes less.  Same general process, just different path

convey, 20 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.

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.

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

Ans is not an allowed I/O method.

According to who?

That didn't work when I tested with 24.

@kamoroso94 Thanks for pointing that out, I had mistakenly put I/Ans instead of Ans/I but it's fixed now.

><>, 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!

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.

Pyke, 5 bytes
1D.f%

Try it here!
1D.f  - first number after 1 where
    % -  i%input != 0

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

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).

Is the +2 for the parameter required? I use a recursive method as well sometimes, but usually I haven't included the parameter input (usually 0 or 1) in the byte-count. Is there a rule for this?

@KevinCruijssen It's outside of a standard call, so yes, I would consider it necessary. I do not know if there is any "rule" for this, but this is the fair-play method as far as I'm concerned.

Japt, 5 bytes
@uX}a

Try it here

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.

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.

Alternative 5 bytes

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.

Trailing xs can always be removed.

@Steffan Oh, true

"In particular, make sure that your answer works for inputs 1 and 2"

@DominicvanEssen Oops, missed that. Fixed now.

Vyxal r, 5 bytes
?Ḋ¬)ṅ

Try it Online!
Or
5 bytes
₌ɾKFh

Try it Online!

Ruby, 28 bytes
->n{(1..n+1).find{|x|n%x>0}}

@GB yep, my bad. I foobed in the golfing stage.

Perl, 25 bytes
sub{1 until$_[0]%++$i;$i}

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.

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.

I believe you can shorten this by getting rid of the !. You would need to change the second line to g1+^@.g00_:00 (switching the direction of the 2 branches)

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

Save 1 byte by deleting the space between [A1] and mod

MATL, 6 bytes
t:\f1)

Try it online!

You need Q after t so that it works for inputs 1 and 2

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

@Henry Pointed out in an attempted edit that you have extra whitespace in your if statement.  It seems x % i > 0 can be replaced with x%i>0.

47 bytes: int n(int x){int y=1;for(;x%++y==0;);return y;}

For future reference (it doesn't really help here, but still), you don't need the for-loop brackets when using a single if statement followed by a function (so for(;;)if(true)x(); would work), and you can use for(;;) instead of while(1>0).

@peech You can use my solution in the comment two above this, you know. ;) Shaves off another two bytes.

yeah i know, but i dont want to take credit for your solution :) you should post it, there's no limitation for one solution per each language :)

@peech My solution isn't significantly different enough to post it separately. :P Please, use it.

hehe ok, thank u very much :)

instead i==0 write i<1

Clojure, 48 Bytes
(defn f[n](some #(if(>(mod n %)0)%)(range 1 n)))

PowerShell, 26 bytes
for(;!("$args"%++$i)){};$i

Try it online!

Other solutions have switched from !() to <1, would that help here too?

@Neil powershell uses bash-style operators, so it would end up being -lt1 (or -eq0), one byte longer unfortunately.

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.

Japt, 8 bytes
U%°V?V:ß

This was inspired by Arnauld's solution.
Thanks ETHproductions for golfing this even more!
Try it Online!

I just realized that V defaults to 0, which allows you to do U%°V?V:ßUV (° is ++). Then you can take advantage of the fact that ß passes in U and V by default to do U%°V?V:ß for only 8 bytes :-)

@ETHproductions Wow, very nice!

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.

REXX, 35 bytes
arg a
do n=1 until a//n>0
end
say n

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.

In the case of an input file with numbers, only the first result is always correct. The following results give the smallest number that doesn't divide the given number and is greater than the previous result, because i is not reinitialized.

Good catch. I can fix it by adding 4 bytes :(

I'm not sure if it needed to be fixed, or if it's enough to not claim that it works with more than one number. A function must be usable more than once, but I think one could argue that here we have a whole program, and giving more than one number is illegal input.

@ChristianSievers I feel bad enough writing code I consider inefficient... to make something that can't be called sequentially in AWK would make me feel truly dirty. :p

I feel you. ;-)

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.

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.

Emojicode, 74 bytes
➡i 10ii➕1ii

Try it online!

C (gcc) 30 bytes
i;f(n){for(i=0;n%++i<1;);i=i;}

Try it online!

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

><>, 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.

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)

Perl 6, 13 bytes
{+(1...$_%*)}

Try it online!

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

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.

Welcome to the site, and nice first answer! I've edited in a link to an online testing environment so that others can test and run your code. You can save 2 bytes by removing the !=0 (Try it online!) and be sure to check out our Tips for golfing in Python page for more ways you could golf your answer.

I got it down to 36, but how is left as an exercise to the reader ;)

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)    |

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

ARBLE, 27 20 bytes
(range(2,n+9)&n%x)/z

Try it online!

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

Vyxal r, 29 bitsv1, 3.625 bytes
?%)ṅ

Try it Online!

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)

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)

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.

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;
}

You don't need all that whitespace, and you can easily save bytes by using shorter identifiers than end and start. On the other hand, you do need to submit either a full program or a function (not a snippet, like you have there), and you current demonstration code is way too long to really serve that role. (I also think you're using rather more verbose control constructs than you need to; in the C family, for is normally best for loops in [tag:code-golf] because it's fairly flexible and it has the shortest name.)

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.

GameMaker Language, 58 bytes
a=argument0 for(i=1;i<=a;i++){if a mod i return i}return i

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))))))

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

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

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

(($1%($2)))&&bc<<<$2||$0 $1 $2+1   to be run as scriptname N 2

@izabera I like the idea of using bc, but I can't get it to be any shorter than the original 37 bytes without the contrivance of passing the extra argument 2.

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.

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.

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 1ø 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.

You can remove the function definition/call entirely: 1[\$@$@$@$@\/*-0=][1+]#. to get 24 bytes. (insert the value to test at the beginning)

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

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).

Java 8, 37 bytes
n->{int i=1;while(n%++i<1);return i;}

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+]#

Julia 0.6, 25 bytes
f(n,x=2)=n%x>0?x:f(n,x+1)

Try it online!

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

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

SNOBOL4 (CSNOBOL4), 57 bytes
F	F =F + 1
	GT(REMDR(N,F))	:S(RETURN)F(F)
	DEFINE('F(N)')

Try it online!

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!

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!

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.

Welcome to PPCG! This is a good first answer, but I think you are assuming that the input is in a variable called n. That is not allowed, because we have some standard Input / Output methods. I think you could modify your code (currently a snippet) to make it either a function, or a full program accepting input from STDIN / Command Line Arguments. I might be wrong, since I don't know Powershell :)

W h d, 7 5 bytes
W is doing pretty great, given its lack of a break-out-of-loop instruction!
▲²!░╠

Explanation
% 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
```

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

@Grimmy Thanks and nice fix. I knew I could fix it by adding a +2, but then it would have the same 6 bytes as the other 05AB1E answer, which is why I deleted it. But using an infinite list is a smart alternative to fix, at the cost of no additional bytes. :)

Perl 5 -p, 15 bytes
1until$_%++$\}{

Try it online!

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.

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!

The code given for the ticker doesn't actually work; If you try pasting in i->i+\{\mod(n,i)=0\} verbatim into the ticker you will find that it doesn't paste anything at all. Usually adding a leading newline to the piecewise expression would fix the issue, but due to some weird quirks regarding pasting expressions into tickers, this won't fix the issue either (it might be because the ticker is inherently a "single-line" expression so the "multi-line" expression copy/paste doesn't take effect).

The only way I can think of to fix this is to separate out the piecewise expression like a=\{\mod(n,i)=0\} so that you can use the multi-line copy/paste, then have i->i+a in the ticker.

@Aiden Chow oh, i just directly set $a$ to the entire action instead

You would need a leading newline in your "expression list" unless you swap the two lines.

Hmmm, I can still paste it without the newline

Oh yep my bad, I pasted the wrong thing.

I also just wanted to mention that taking in input in hardcoded variables is heavily discouraged if not outright banned by the community, which is what you are doing here with n.

I have a solution with list manipulations, but is longer and doesn't work for $n>10000$ because of the list length limit. Should i post that instead?

It is fine if your program cannot handle all test cases due to an inherent language restriction as long as it theoretically would work for every single case without those restrictions (I don't have a meta post on hand about this but I remember this being true), so the solution you are thinking of (probably the same solution that I'm thinking of) is completely fine.

As for creating programs with actions, it used to be that you can use \ans to get input as that is an acceptable form of input, but recently Desmos has taken that functionality out of the main graphing calculator so that doesn't work anymore.

As for right now, there doesn't seem to be a "meta-compliant" way to get input for actions as far as I can tell. Maybe I'll ask in TNB if hardcoding is okay for now as a special case.

would (byte count aside) having a function initialize the variables, and then starting the ticker, work?

Hmmm I don't see anything immediately wrong with it, though I'll have to ask to make sure because it does seem like a weird I/O method.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
What did I just play? Translate guitar fingerings to chords
Related: Music: what's in this chord?, Notes to Tablature, Generating guitar tabs?, Translate number pairs to guitar notes
Given a guitar fingering, output the chord it represents. You can use standard input and output, or write a function that returns a string.
The input fingerings will be classifiable as one of the following chords, to be expressed as follows (if the root note were C):

major triad: C
minor triad: Cm
(dominant) seventh: C7
minor seventh: Cm7

The chord might be inverted, so you can't rely on the lowest note being the root. Nor can you rely on this being an easy or common fingering in the real world. More generally, your program's output must ignore the octaves of the pitches, and treat all pitches that correspond to the same musical note (i.e., A) as equal.
This is code-golf, so the shortest code in bytes wins.
Input format
The input is a series of 6 values that indicate, for each string of a 6-string guitar in standard tuning (E A D G B E), which fret that string will be played at. It could also indicate that the string is not played at all. The "zeroth" fret is also known as the open position, and fret numbers count up from there. Assume the guitar has 21 fret positions, such that the highest fret position is number 20.
For example, the input X 3 2 0 1 0 means placing ones fingers at the following positions at the top of the guitar's neck:
(6th) |---|---|---|---|---
      |-X-|---|---|---|---
      |---|---|---|---|---
      |---|-X-|---|---|---
      |---|---|-X-|---|---
(1st) |---|---|---|---|---

and strumming the 2nd through the 6th strings. It corresponds to this ASCII tab:
e |-0-|
B |-1-|
G |-0-|
D |-2-|
A |-3-|
E |---|

You have some flexibility in choosing the kind of input you want: each fret position can be expressed as a string, or a number. Guitar strings that are not played are commonly indicated with an X, but you can choose a different sentinel value if that makes it easier for you (such as -1 if you're using numbers). The series of 6 fret positions can be input as any list, array, or sequence type, a single space-separated string, or as standard input—once again, your choice.
You can rely on the input corresponding to one of the 4 chord types mentioned above.
Please explain in your post what form of input your solution takes.
Output format
You must either return or print to standard output a string describing the chord the fingering is for. This string is composed of two parts concatenated together. Capitalization matters. Trailing whitespace is allowed.
The first part indicates the root note, one of A, A#/Bb, B, C, C#/Db, D, D#/Eb, E, F, F#/Gb, G, or G#/Ab. (I'm using # instead of ♯, and b instead of ♭, to avoid requiring Unicode.) Root notes that can be expressed without a sharp or flat must be expressed without them (never output B#, Fb, or Dbb); those that cannot must be expressed with a single sharp or flat symbol (i.e. either C# or Db, but never B##). In other words, you must minimize the number of accidentals (sharps or flats) in the note's name.
The second part indicates the type of chord, either empty for a major triad, m for a minor triad, 7 for the dominant seventh, or m7 for the minor seventh. So a G major is output simply as G, while a D♯ minor seventh could be output as either D#m7 or Ebm7. More examples can be found in the test cases at the end.
Theory & hints
Musical notes
The chromatic scale has 12 pitches per octave. When tuned to equal temperament, each of these pitches is equally distant from its neighbors1. Pitches that are 12 semitones apart (an octave) are considered to be the same musical note. This means we can treat notes like integers modulo 12, from 0 to 11. Seven of these are given letter names2 from A to G. This isn't enough to name all 12 pitches, but adding accidentals fixes that: adding a ♯ (sharp) to a note makes it one semitone higher, and adding a ♭ (flat) makes it one semitone lower.
Chords
A chord is 2 or more notes played together. The type of chord depends on the relationships between the notes, which can be determined by the distances between them. A chord has a root note, as mentioned earlier. We'll treat the root note as 0 in these examples, but this is arbitrary, and all that matters in this challenge is the distance between notes in modulo arithmetic. There will always be one unique chord type for the answer, either a triad or a seventh chord. The root note will not always be the lowest-frequency pitch; choose the root note such that you can describe the chord as one of the four following chord types:

A major triad is a chord with the notes 0 4 7.
A minor triad is a chord with the notes 0 3 7.
A dominant (or major/minor) seventh chord has the notes 0 4 7 10.
A minor (or minor/minor) seventh chord has the notes 0 3 7 10.3

Guitar tuning
Standard tuning on a 6-string guitar starts with E on the lowest string, and then hits notes at intervals of 5, 5, 5, 4, then 5 semitones going up the strings. Taking the lowest E as 0, this means strumming all the strings of the guitar gives you pitches numbered 0 5 10 15 19 24, which modulo 12 is equivalent to 0 5 10 3 7 0, or the notes E A D G B E.
Worked examples
If your input is 0 2 2 0 0 0, this corresponds to the notes E B E G B E, so just E, B, and G. These form the chord Em, which can be seen by numbering them with the root as E, giving us 0 3 7. (The result would be the same for X 2 X 0 X 0, or 12 14 14 12 12 12.)
If your input is 4 4 6 4 6 4, numbering these with a root of C♯ gives 7 0 7 10 4 7, or 0 4 7 10, so the answer is C#7 (or Db7). If it was instead 4 4 6 4 5 4, the numbering would give 7 0 7 10 3 7, or 0 3 7 10, which is C#m7 (or Dbm7).
Test cases
X 3 2 0 1 0  --->  C
0 2 2 0 0 0  --->  Em
X 2 X 0 X 0  --->  Em
4 4 6 4 6 4  --->  C#7  (or Db7)
4 4 6 4 5 4  --->  C#m7 (or Dbm7)
0 2 2 1 0 0  --->  E
0 0 2 2 2 0  --->  A
X X 4 3 2 2  --->  F#   (or Gb)
3 2 0 0 0 1  --->  G7
X X 0 2 1 1  --->  Dm7
3 3 5 5 5 3  --->  C
4 6 6 5 4 4  --->  G#   (or Ab)
2 2 4 4 4 5  --->  B7
0 7 5 5 5 5  --->  Am7
7 6 4 4 X X  --->  B
8 6 1 X 1 3  --->  Cm
8 8 10 10 9 8 -->  Fm
0 19 5 16 8 7 -->  Em
6 20 0 3 11 6 -->  A#   (or Bb)
X 14 9 1 16 X -->  G#m  (or Abm)
12 14 14 12 12 12 --> Em
15 14 12 12 12 15 --> G
20 X 20 20 20 20  --> Cm7
X 13 18 10 11 10  --> A#7 (or Bb7)

1by the logarithms of their frequencies
2or, in solfège, names like do, re, mi. In this challenge, use the letter names.
3This could also be called a major sixth chord, with a different choice of root note. In this challenge, call it by its minor seventh name.

Great challenge!

Tempted to close as a dupe from my future challenge :D (I had a very similar challenge in mind, but you were obvously quicker.)

Is trailing whitespace allowed in the output string?

@LuisMendo sure; that's fine.

Are there any cases where the chord cannot be named or sth like that? like augmented chords?

@officialaimm no, you don't need to handle any other situations. You can assume it will always be one of those 4 chord types. In other words, your code can do whatever you want (including error or give a wrong answer) if it gets a different chord.

MATL, 115 114 bytes
[OAXICO]+tZN~)Y@!"@t1)XH- 12\XzXJK7hm?O.]JI7hm?'m'.]J[KCX]m?'7'.]J[ICX]m?'m7'.]]'FF#GG#AA#BCC#DD#E'l2741B~QY{HX)wh

Input format is [N 3 2 0 1 0], where N indicates unused string.
The output string always uses #, not b.
Try it online! Or verify all test cases, in two parts to avoid the online compiler timing out:

Test cases 1‒12;
Test cases 13‒24.

Explanation
[OAXICO]            % Push [0 5 10 3 7 0]. This represents the pitch of each open
                    % string relative to the lowest string, modulo 12
+                   % Add to implicit input. May contain NaN's, for unused strings
tZN~)               % Remove NaN's
Y@!                 % Matrix of all permutations, each in a column
"                   % For each column
  @                 %   Push current column
  t1)               %   Duplicate and get first entry
  XH                %   Copy into clipboard H
  - 12\             %   Subtract. This amounts to considering that the first note
                    %   of the current permutation is the root, and computing
                    %   all intervals with respect to that
  12\               %   Modulo 12
  Xz                %   Remove zeros
  XJ                %   Copy into clipboard J
  K7hm?             %   Are all intervals 4 or 7? If so: it's a major chord
    O               %     Push 0 (will become space when converted to char)
    .               %     Break for loop
  ]                 %   End if
  J                 %   Push array of nonzero intervals again
  I7hm?             %   Are all intervals 3 or 7? If so: it's a minor chord
    'm'             %     Push this string
    .               %     Break for loop
  ]                 %   End if
  J                 %   Push array of nonzero intervals again
  [KCX]m?           %   Are all intervals 4, 7 or 10? If so: it's a dominant-7th
                    %   chord
    '7'             %     Push this string
    .               %     Break for loop
  ]                 %   End if
  J                 %   Push array of nonzero intervals again
  [ICX]m?           %   Are all intervals 3, 7 or 10? If so: it's a minor 7th chord
    'm7'            %     Push this string
    .               %     Break for loop
  ]                 %   End if
]                   % End for. The loop is always exited via one of the 'break'
                    % statements. When that happens, the stack contains 0, 'm',
                    % '7' or 'm7', indicating the type of chord; and clipboard H
                    % contains a number that tells the root note using the lowest
                    % string as base (1 is F, 2 is F# etc)
'FF#GG#AA#BCC#DD#E' % Push this string. Will be split into strings of length 1 or 2
l                   % Push 1
2741B~Q             % Push [1 2 1 2 1 2 1 1 2 1 2 1] (obtained as 2741 in binary,
                    % negated, plus 1)
Y{                  % Split string using those lengths. Gives a cell array of
                    % strings: {'F', 'F#', ..., 'E'}
H                   % Push the identified root note
X)                  % Index into cell array of strings
wh                  % Swap and concatenate. Implicitly display

MS-DOS .COM file (179 bytes)
The file (here displayed as HEX):
fc be 81 00 bf 72 01 31 db b9 06 00 51 e8 73 00
59 e2 f9 b9 0c 00 be 48 01 ad 39 c3 74 0d 40 75
f8 d1 fb 73 03 80 c7 08 e2 ec c3 31 db 88 cb 8a
87 59 01 e8 42 00 8a 87 65 01 e8 3b 00 81 c6 08
00 ac e8 33 00 ac eb 30 91 00 89 00 91 04 89 04
ff ff 00 00 6d 00 37 00 6d 37 42 41 41 47 47 46
46 45 44 44 43 43 00 23 00 23 00 23 00 00 23 00
23 00 04 09 02 07 0b 04 84 c0 74 06 b4 02 88 c2
cd 21 c3 8a 0d 47 ac 3c 20 76 fb 30 ed 3c 41 73
22 2c 30 72 0b 86 c5 b4 0a f6 e4 00 c5 ac eb ed
88 e8 00 c8 30 e4 b1 0c f6 f1 88 e1 b8 01 00 d3
e0 09 c3

The input is given via command line. Invalid input will lead to invalid program behaviour!
The assembler code looks like this:
.text
.code16
ComFileStart:
    cld
    mov $0x81, %si
    mov $(TuneTable-ComFileStart+0x100), %di
    xor %bx, %bx
    # 6 strings: Build the mask of played tones
    mov $6, %cx
NextStringRead:
    push %cx
    call InsertIntoMask
    pop %cx
    loop NextStringRead

    # Check all base tones...
    mov $12, %cx
TestNextTone:
    mov $0x100+ChordTable-ComFileStart, %si
TestNextChord:
    lodsw
    # Is it the chord we are searching for?
    cmp %ax, %bx
    je FoundChord
    # Is it the end of the table?
    inc %ax
    jnz TestNextChord
    # Transpose the chord we really play
    # and go to the next tone
    # This code rotates the low 12 bits of
    # BX one bit right
    sar $1, %bx
    jnc NoToneRotated
    add $8, %bh
NoToneRotated:
    loop TestNextTone
EndOfProgram:
    ret

FoundChord:
    # Get and print the tone name
    xor %bx, %bx
    mov %cl, %bl
    mov (ToneNamesTable+0x100-1-ComFileStart)(%bx),%al
    call printChar
    mov (ToneNamesTable+0x100+12-1-ComFileStart)(%bx),%al
    call printChar
    # Get the chord name suffix and print it
    add $(ChordNamesTable-ChordTable-2),%si
    lodsb
    call printChar
    lodsb
    # Note: Under MS-DOS 0x0000 is the first word on
    # the stack so the "RET" of printChar will jump
    # to address 0x0000 which contains an "INT $0x21"
    # (end of program) instruction
    jmp printChar

ChordTable:
    # Major, Minor, Major-7, Minor-7
    .word 0x91, 0x89, 0x491, 0x489, 0xFFFF
ChordNamesTable:
    .byte 0,0,'m',0,'7',0,'m','7'
ToneNamesTable:
    .ascii "BAAGGFFEDDCC"
    .byte 0,'#',0,'#',0,'#',0,0,'#',0,'#',0
TuneTable:
    .byte 4,9,2,7,11,4

#
# Subfunction: Print character AL;
#              Do nothing if AL=0
#
printChar:
    test %al, %al
    jz noPrint
    mov $2, %ah
    mov %al, %dl
    int $0x21
noPrint:
    ret

#
# Subfunction: Get one finger position
#              and insert it into a bit mask
#              of tones being played
#
# Input:
#
#   [DS:DI] =
#        Tuning of current string (0=C, 1=C#, ..., 11=B)
#        Actually only 2=D, 4=E, 7=G, 9=A and 11=B are used
#
#   DS:SI = Next character to read
#
#   DF = Clear
#
# Input and Output:
#
#    BX = Bit mask
#    DI = Will be incremented
#
# Destroys nearly all registers but SI and BX
#
InsertIntoMask:
    mov (%di), %cl
    inc %di
SkipSpaces:
    lodsb
    cmp $' ', %al
    jbe SkipSpaces
# Now evaluate each digit
    xor %ch, %ch
GetNextDigit:
    # Number = 10*Number+Digit
    cmp $'A', %al
    jae DigitIsX
    sub $'0', %al
    jb DigitsDone
    xchg %al, %ch
    mov $10, %ah
    mul %ah
    add %al, %ch
    lodsb
    jmp GetNextDigit
DigitsDone:
    # Add the tune of the string
    # and perform modulus 12
    mov %ch, %al
    add %cl, %al
    xor %ah, %ah
    mov $12, %cl
    div %cl
    mov %ah, %cl
    mov $1, %ax
    shl %cl, %ax
    or %ax, %bx
DigitIsX:
    ret

Test cases:
6 20 0 3 11 6 -->  A#   (or Bb)

I already saw two piano players playing together "four handed" on a piano.
This test case is the first time I read about guitar players doing this!
Even with right-hand tapping you cannot play a cord like this!

Hmm, maybe a squid could play that chord? I think that's one of the ones I found by a random search so that there could be some "hard" test cases.

Ruby, 129 bytes
As previous version but uses a single loop, with ternary operator to sequence between the parsing step and output step. Some other minor modifications were required to make this work.
->a{r=0
18.times{|j|j<6?a[j]&&r|=8194<<(6--~j%5+a[j]*7)%12:(r/=2)&11==3&&puts("CGDAEBF"[j%7]+?#*(j/13)+['',?m,?7,'m7'][r>>9&3])}}

Ruby, 136 bytes
Llamda function accepts an array of 6 numbers as an argument and outputs to stdout. Unused string is represented by a falsy value (the only falsy values in ruby are nil and false.)
->a{r=0
6.times{|j|a[j]&&r|=4097<<(6--~j%5+a[j]*7)%12}
12.times{|j|r&11==3&&puts("FCGDAEB"[j%7]+?#*(j/7)+['',?m,?7,'m7'][r>>9&3]);r/=2}}

Explanation
I use a representation of the 12 pitches based on the circle of fifths .
This means each pitch is followed by the pitch 7 semitones higher (or 5 semitones lower) giving the sequence F C G D A E B F# C# G# D# A#. There are 2 advantages to this. One is that all the sharps appear together. The other is that the open-string notes of the 5 string bass appear together: GDAEB (the guitar is related but slightly more complex, see below).
The first loop runs 6 times. The expression 6--~j%5(equivalently 6-(j+1)%5) gives the note values for the open strings: E=5 A=4 D=3 G=2 B=6 E=5. To this we add the fret number multiplied by 7 (as can be seen above, adding one semitone moves us 7 places forward in the sequence.) Then we take the whole thing modulo 12 and make a bitmap of the notes that are present (we use 4097<<note value to give 2 consecutive octaves.)
Having composed the bitmap, we are ready to search the chord and output it.
We are interested in the following notes:
Note       position in      position in             Note      position in
           semitone domain  circle of fifths                  circle of fifths
Root       0                0                       Root      0
Minor 3rd  3                9                       Fifth     1
Major 3rd  4                4                       Sixth     3
Fifth      7                1                       Major 3rd 4
Sixth      9                3                       Minor 3rd 9
Minor 7th  10               10                      Minor 7th 10

Starting by checking for chord F, we test to see if the root and fifth are present: bits 0 and 1 (counting from least significant: the 1's and 2's bits.) In order to reject sixth chords we also need to check that the sixth is absent: bit 3 (8's bit.) so we check that r&&11==3 and if so we print the chord.
We ignore the major third, and rely entirely on bit 9 (minor third) and bit 10 (minor 7th) to work out the chord type. The expression r>>9&3 is used to pick the correct chord type from an array.
At the end of the loop, we shift the bitmap right one bit r/=2 to test the possible chord roots in sequence: F C G D A E B F# C# G# D# A#.
Ungolfed in test program
f=->a{                            #Accept array of 6 numbers as argument.
  r=0                             #Setup an empty bitmap.

  6.times{|j|                     #For each string
    a[j]&&                        #if the fret value is truthy (not nil or false)
    r|=4097<<(6--~j%5+a[j]*7)%12  #calculate the note value in the circle of fifths and add to the bitmap.
  }

  12.times{|j|                    #For each possible root note
    r&11==3&&                     #if root and fifth are present (bits 0 and 1) and sixth is absent (bit 3)
    puts("FCGDAEB"[j%7]+?#*(j/7)+ #output the note name and a sharp symbol if necessary, followed by
    ['',?m,?7,'m7'][r>>9&3])      #m and/or 7 as indicate by bits 9 and 10.
    r/=2
  }
}

print 1;f[[nil,3,2,0,1,0]]       #  C
print 2;f[[0,2,2,0,0,0]]         #  Em
print 3;f[[nil,2,nil,0,nil,0]]   #  Em
print 4;f[[4,4,6,4,6,4]]         #  C#7
print 5;f[[4,4,6,4,5,4]]         #  C#m7
print 6;f[[0,2,2,1,0,0]]         #  E
print 7;f[[0,0,2,2,2,0]]         #  A
print 8;f[[nil,nil,4,3,2,2]]     #  F#
print 9;f[[3,2,0,0,0,1]]         #  G7
print 10;f[[nil,nil,0,2,1,1]]    #  Dm7
print 11;f[[3,3,5,5,5,3]]        #  C
print 12;f[[4,6,6,5,4,4]]        #  G#
print 13;f[[2,2,4,4,4,5]]        #  B7
print 14;f[[0,7,5,5,5,5]]        #  Am7
print 15;f[[7,6,4,4,nil,nil]]    #  B
print 16;f[[8,6,1,nil,1,3]]      #  Cm
print 17;f[[8,8,10,10,9,8]]      #  Fm
print 18;f[[0,19,5,16,8,7]]      #  Em
print 19;f[[6,20,0,3,11,6]]      #  A#
print 20;f[[nil,14,9,1,16,nil]]  #  G#m
print 21;f[[12,14,14,12,12,12]]  #  Em
print 22;f[[15,14,12,12,12,15]]  #  G
print 23;f[[20,nil,20,20,20,20]] #  Cm7
print 24;f[[nil,13,18,10,11,10]] #  A#7

Javascript (ES6), 335 333 bytes
Love this challenge and PPCG SE! This is my first golf - suggestions welcome as I'm sure it could be improved a lot.
(knocked off 2 bytes as I had included f= in the count)
Function f takes an array of strings, representing numbers and 'X', like f(['X','3','2','0','1','0']) and returns a chord (natural or sharp) like E#m7. Newlines added for clarity (not included in byte count)
f=c=>[s=new Map([[435,''],[345,'m'],[4332,7],[3432,'m7']]),
n=[...new Set(c.map((e,i)=>e?(+e+[0,5,10,3,7,0][i])%12:-1)
.filter(e=>++e).sort((a,b)=>a>b))],d=[...n,n[0]+12].reduce(
(a,c,i)=>i?[...a,(c-n[i-1]+12)%12]:[],0).join``.repeat(2),
m=+d.match(/(34|43)(5|32)/g)[0],'E0F0F#0G0G#0A0A#0B0C0C#0D0D#'
.split(0)[n[d.indexOf(m)]]+s.get(m)][4]

Usage example:
console.log(f(['0','2','2','0','0','0'])); // Em

To run test cases:
tests=`X 3 2 0 1 0 ---> C
0 2 2 0 0 0 ---> Em
X 2 X 0 X 0 ---> Em
4 4 6 4 6 4 ---> C#7 (or Db7)
4 4 6 4 5 4 ---> C#m7 (or Dbm7)`; // and so on...

tests.split`\n`.forEach(e=>{
    console.log(`Test: ${e}
      Result: ${f(e.split(' ').slice(0,6))}`)
})

Ungolfed version with explanation:
f = (c) => {
    s = new Map([
        [435,''], [345,'m'], [4332,7], [3432,'m7']
    ]) /* Each key in s describes the intervals (semitones)
          between consecutive notes in a chord, when it is
          reduced to a single octave, including the interval
          from highest back to lowest. The values describe
          the corresponding chord suffix. E.g. C-E-G has
          intervals C-4-E-3-G-5-C. 435=major=no suffix. */

    n = [ ...new Set(
        c.map(
         (e,i) => e ? ( +e + [0,5,10,3,7,0][i] )%12 : -1
         ).filter( (e) => ++e ).sort( (a,b) => a>b )
        ) ] /* take the input array, c, and transform each fret
               position into a note. remove non-notes (-1), sort
               in tone order, remove duplicates. An input of
               positions X 13 18 10 11 10 becomes notes
               (-1) 6 4 1 6 10 then 1 4 6 10. */

    d = [ ...n, n[0] + 12 ].reduce(
        (a,c,i) => i ? [ ...a, (c - n[i-1] + 12)%12 ] : [], 0
    ).join``.repeat(2)
    /* convert the note array, n, into an interval string, d,
       including the lowest note repeated above it to capture
       all intervals. Repeat it twice so that, regardless of the
       inversion played, the intervals will appear in root order
       somewhere. E.g. notes 1-4-6-10 and 13 (1+12)
       become intervals 3 2 4 3, and string for searching
       32433243 */

    m = +d.match( /(34|43)(5|32)/g )[0];
      /* m is the matched chord pattern. In this case, 4332. */

    return 'E0F0F#0G0G#0A0A#0B0C0C#0D0D#'.split(0)[
    n[ d.indexOf(m) ]
    /* get the position in the interval string where the root
       interval first occurs. this corresponds to the position
       of the chord root note in the note array, n. convert this
       number 0-12 to a note name E - D# */
    ] + s.get(m)
       /* add the suffix corresponding to the matched
       chord interval pattern */
}

Welcome to the site! I'm glad to hear you enjoy it. :) Unfortunately, I don't know any JS so I don't have any tips, but you might be able to find some here

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Error (or warning) quine that's also a regular quine
(Inspired by this comment on an old question.)
Background
An error quine (also known as a "Kimian quine") is a program which, when compiled or run, causes the compiler/interpreter/runtime to print an error message that has identical text to the program itself, and nothing else. For the purposes of this challenge, we're defining "error" broadly, to include warnings too.
Task
In this challenge, we're looking for a quine which is also an error quine. When executed, the program must print its own source code normally (i.e. not as an error/warning message); this must be a proper quine (i.e. some part of the program must encode a different part of the output). Additionally, compiling and executing the program must also cause the program's source code – and nothing else – to be printed as error or warning messages by the implementation. (Note that this means that you will not be able to use compile-time errors, in languages where those prevent the program from executing normally.) So in other words, the program's source code will be printed twice, once via each method.
Clarifications

In most cases, it'll be obvious what is and isn't an error/warning message; we aren't distinguishing between the two here. In ambiguous cases, define an error/warning message as any text that's output by the implementation either: 1. as a consequence of something other than executing a command (or whatever the closest equivalent is in the language); or 2. that wasn't part of the input to the command that produced it as output.
The error/warning part of the quine doesn't need to be a proper quine (although in most cases it will be by chance, as most error and warning messages contain considerable amounts of fixed text).
It's acceptable for the program to output multiple errors/warnings, which form the program's source when concatenated together. It's not acceptable to output errors/warnings that don't appear in the source.
Unlike in many challenges, the switches given to the compiler, and the program filename, are likely to be highly relevant in this challenge. Given that the challenge may not be possible otherwise, I'm willing to be flexible here, although if you run the implementation in an unusual way, remember that PPCG rules charge a byte penalty for doing so (equal to the number of additional characters that you'd need to add on the command line over the shortest "normal" way to run a program), and thus you'll need to specify the size of the penalty in your post. (For example, if the interpreter you're using reads the program from a file, and has no particular restrictions on the filename, the shortest normal way to run the program would be from a file with a 1-character filename; thus, if you need a 100-character filename to make your program work, you'd incur a byte penalty of +99.)
The compiler/interpreter version you use may well be relevant, so as part of your submission, please state a specific compiler or interpreter on which your program works, and which version is required. (For example, a C submission might state "C (gcc 6.2.0)" in the header.)
Note that this task may not be possible in all languages. In the languages where it is, the easiest method will likely be to find an error or warning message for which it's possible to customize some subset of the text (via changing the name of something that gets quoted in the message; filenames are a common choice here, but not the only one). I'll be particularly impressed (and surprised) if someone finds a way to do this using only error and warning messages whose text is fixed.

Victory condition
This is a code-golf challenge, so an entry is considered to be better if it has a smaller byte count. As such, once you've got your program working at all, you want to optimize it to bring the number of bytes down as far as possible. (However, don't be discouraged if there's already a shorter entry, especially if it's in a different language; what we're really looking for here is to shorten a particular algorithm or idea behind a program as much as possible, but seeing multiple solutions in different languages or that rely on different principles is always worthwhile.)

As I said in chat, I think the first bullet point is unclear. In most cases, it'll be obvious what is and isn't an error/warning message just serves as a starting point to discussions and language-lawyering.

@Dennis: I agree in principle that the situation isn't great, but on the other hand can't think of a concrete way to improve it; removing the exception for things that are obviously error messages is likely to lead to some very unintended situations in some languages, which may well cause more damage than it cures; if you think you can improve the question, I have no objection to it being edited (and I don't really think questions on PPCG should have "ownership" anyway, although that's a different issue)

As it is, I think the question is unclear and lacking an objective validity criterion. I agree that my proposed change may make things even worse. One possible course of action would be to put the challenge on hold and repost it in the sandbox.

It may be worth closing the question merely because the majority of the answers don't comply with the specification (even the parts that are explicitly stated). My experience is that such problems tend to end up leaving everyone unsatisfied, and can't be fixed via making the question clearer.

I've put the challenge on hold for now. I do hope you reconsider reposting it in the sandbox. It's a very interesting idea, and it would be a shame to let it go to waste.

Sandbox post is here. (I was considering editing that into the question, but that would put the post into the reopen queue, which would be highly counterproductive as it would make it harder to reopen if and when the issues had been resolved.)

IIRC, the CPP has something like #warning "Blablabla" which prints the whole line the warning is on, then the stuff in double quotes.

I think "error/warning" can be defined as the following (in addition to the existing rules): 1. Anything not defined by the specification 2. Causing a nonzero exit code 3. Anything which is prepended by "warning" or "error" by the compiler with the desired compilation settings 4. An instruction that prints to stderr that also causes an exit of the program. I don't think there are other edgecases.

@noɥʇʎԀʎzɐɹƆ: 1. isn't going to work, because not all languages have a specification; 2. isn't going to work due to a false positive for commands like exit; 3. won't work in many languages, even if you force locale to C or to English; 4. has already caused problems in the answers below. So I don't think that works.

JavaScript (Firefox 50), 153 bytes
Error: "Error: 1.replace(/.+/,x=>{alert(x=x.replace(1,uneval(x)));throw x.slice(7)})".replace(/.+/,x=>{alert(x=x.replace(1,uneval(x)));throw x.slice(7)})

Explanation
The idea here was to start with the most easily modifiable JS quine I've found yet:
".replace(/.+/,x=>alert(uneval(x)+x))".replace(/.+/,x=>alert(uneval(x)+x))

The throw keyword is a simple way to make it throw its own code as well:
".replace(/.+/,x=>{alert(x=uneval(x)+x);throw x})".replace(/.+/,x=>{alert(x=uneval(x)+x);throw x})

However, there's a slight problem: Firefox prepends the thrown message with Error:. Fortunately, Error: mycode is actually valid JavaScript! (To learn more about this, visit MDN.)
Error: ".replace(/.+/,x=>{alert(x=uneval(x)+x);throw x})Error: ".replace(/.+/,x=>{alert(x=uneval(x)+x);throw x})

Oops, this alerts the wrong thing:
".replace(/.+/,x=>{alert(x=uneval(x)+x);throw x})Error: ".replace(/.+/,x=>{alert(x=uneval(x)+x);throw x})Error:

Since the quotation mark is no longer at the start of the code, uneval(x)+x won't give us the correct result. The best way to fix this is to add a placeholder in place of the nested string:
Error: "Error: 1.replace(/.+/,x=>{alert(x=x.replace(1,uneval(x)));throw x})".replace(/.+/,x=>{alert(x=x.replace(1,uneval(x)));throw x})

Uh-oh, now there's an extra Error: in the error message. Let's fix that by slicing the string:
Error: "Error: 1.replace(/.+/,x=>{alert(x=x.replace(1,uneval(x)));throw x.slice(7)})".replace(/.+/,x=>{alert(x=x.replace(1,uneval(x)));throw x.slice(7)})

And finally, both the output and the error message are identical to the code! I'd add a Stack Snippet, but it doesn't seem to work in a snippet in any browser.

Python 2, 217 80 51 bytes
The trailing linefeed is required.
s='s=%r;print s%%s;exit(s%%s)';print s%s;exit(s%s)

Try it online
I started with a simple quine:
s='s=%r;print s%%s';print s%s

Then I added raise on the end to throw an IOError.
s='s=%r;print s%%s;raise IOError(s%%s)';print s%s;raise IOError(s%s)

Unfortunately, the traceback was causing problems (I couldn't make it go away completely), and the name of the exception was always printed in front like IOError: <code here>, even if I removed the traceback.
Then I found this helpful SO answer and modified it for my purposes.
Then I found that I can skip creating my own class and can just use sys.exit, making my code much shorter.

I don't think this complies with the definition of error in the challenge spec since it's not as a consequence of something other than executing a command nor it wasn't part of the input to the command that produced it as output. That said, plain exit works just fine here. No need for sys.

Let us continue this discussion in chat.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/