Find the smallest number that doesn't divide N

51

4

This challenge is simple enough that it's basically all in the title: you're given a positive integer N and you should return the smallest positive integer which is not a divisor of N.

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

This is OEIS sequence A007978.

Rules

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

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

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

Test Cases

The first 100 terms are:

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

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

And for some larger test cases:

N          f(N)
1234567    2
12252240   19
232792560  23

Leaderboard

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

/* Configuration */

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];
  
  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });
    
    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    
  });
  
  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;
    
    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/<a/.test(lang)) lang = jQuery(lang).text();
    
    languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
  });

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

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

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

}
body { text-align: left !important}

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

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

table thead {
  font-weight: bold;
}

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

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

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

Martin Ender

Posted 2017-01-03T08:50:00.077

Reputation: 184 808

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. – Carcigenicate – 2017-01-06T00:05:08.273

1That 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. – CalculatorFeline – 2018-01-31T04:41:03.863

Answers

18

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.

Greg Martin

Posted 2017-01-03T08:50:00.077

Reputation: 13 940

Very interesting way to loop without using For, While, etc – ngenisis – 2017-01-03T17:07:25.833

5I learned it from this site! I'm definitely enjoying learning more about Mathematica by being here (can I justify that on my timesheet...?). – Greg Martin – 2017-01-03T17:49:48.273

3That does not look like mathematica O_o – Mama Fun Roll – 2017-01-03T19:14:34.217

2don't let the lack of capital letters and brackets fool ya ;) – Greg Martin – 2017-01-03T20:22:44.543

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

– ngenisis – 2017-01-04T00:57:38.770

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!. – Greg Martin – 2017-01-04T01:34:20.810

What does "until it stops mattering" mean? – Cyoce – 2017-01-05T09:52:41.860

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. – Greg Martin – 2017-01-05T18:32:37.463

1Actually only 28436 digits. – user202729 – 2018-02-22T07:20:08.080

14

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.

busukxuan

Posted 2017-01-03T08:50:00.077

Reputation: 2 728

2Saw the problem, made this answer, came here to post it, found yours. Well done! – isaacg – 2017-01-04T10:08:38.577

I wrote this and felt awesome about myself: .V1In%Qb0bB Saw your answer, and not feeling so awesome anymore. – John Red – 2017-01-05T10:28:41.970

@JohnRed Lol, I think you just need to familiarize yourself with the built-ins in Pyth. – busukxuan – 2017-01-05T10:34:07.253

14

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

Arnauld

Posted 2017-01-03T08:50:00.077

Reputation: 111 334

Exactly what I got. I'd be surprised if anything shorter is possible – ETHproductions – 2017-01-03T20:25:49.247

@ETHproductions On second thought, there's a shorter one. :-) – Arnauld – 2017-01-03T20:31:40.990

5Um. That's... uh... wow. – ETHproductions – 2017-01-03T20:33:52.563

13

Python, 43 36 35 bytes

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

orlp

Posted 2017-01-03T08:50:00.077

Reputation: 37 067

13

Hexagony, 12 bytes

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

Embiggened:

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

Try it online!

Sok

Posted 2017-01-03T08:50:00.077

Reputation: 5 592

2That's a very impressive score for Hexagony, nice work! – Martin Ender – 2017-01-03T09:51:06.440

11

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.

rturnbull

Posted 2017-01-03T08:50:00.077

Reputation: 3 689

Nice, just wanted to suggest using which.min, but then I saw the edit and it seems match does a similar job. – JAD – 2017-01-03T10:34:43.713

2Also, nice trick using T, saving the need to define it before the while loop. – JAD – 2017-01-03T10:36:05.220

@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.) – rturnbull – 2017-01-03T10:40:13.933

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. – asac – 2017-01-04T17:52:09.793

@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. – rturnbull – 2017-01-05T00:14:16.520

10

Haskell, 26 bytes

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

Everyone forgets about until!

xnor

Posted 2017-01-03T08:50:00.077

Reputation: 115 687

9

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.

user62131

Posted 2017-01-03T08:50:00.077

Reputation:

1Never thought about doing that, that's neat! – Fatalize – 2017-01-03T10:38:58.917

8

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

Fatalize

Posted 2017-01-03T08:50:00.077

Reputation: 32 976

8

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.

Gabriel Benamy

Posted 2017-01-03T08:50:00.077

Reputation: 2 827

7

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

Emigna

Posted 2017-01-03T08:50:00.077

Reputation: 50 798

Nice, I was wondering how you'd do this iteratively in 05AB1E. – Magic Octopus Urn – 2017-01-03T15:36:23.833

7

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

Giacomo Garabello

Posted 2017-01-03T08:50:00.077

Reputation: 1 419

7

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

user62131

Posted 2017-01-03T08:50:00.077

Reputation:

Damn you Jelly! Pyth beats you today! :D – John Red – 2017-01-05T10:38:40.837

ASCII-only: 2%@1# – Erik the Outgolfer – 2018-01-30T20:08:20.087

6

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

Dada

Posted 2017-01-03T08:50:00.077

Reputation: 8 279

6

C#, 39 37 bytes

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

Saved two bytes thanks to Martin!

Alfie Goodacre

Posted 2017-01-03T08:50:00.077

Reputation: 321

I like while(!(n%++i)); better but of course, this is code golf and 1 byte is 1 byte. – John Hamilton – 2017-01-03T12:57:19.147

Does that work? I didn't know that the 0 evaluated to false automatically – Alfie Goodacre – 2017-01-03T15:40:53.390

Ah, I tried it in C++, yeah it doesn't work with C#. – John Hamilton – 2017-01-04T07:31:28.507

6

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!

flawr

Posted 2017-01-03T08:50:00.077

Reputation: 40 560

@(n)find(mod(n,1:n+1),1) is shorter, isn't it? – Giuseppe – 2018-01-30T22:05:10.980

it is indeed, thanks! – flawr – 2018-01-30T22:57:54.793

6

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.

Magic Octopus Urn

Posted 2017-01-03T08:50:00.077

Reputation: 19 422

@Zgarb missed that part, initial increment by 2 fixes the problem. – Magic Octopus Urn – 2017-01-03T16:08:56.987

1Nice! I always forget that 05ab1e has a divisor function :) – Emigna – 2017-01-03T18:30:22.610

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.

– Kevin Cruijssen – 2020-01-22T14:09:45.777

6

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.

Dennis

Posted 2017-01-03T08:50:00.077

Reputation: 196 637

5

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

steenbergh

Posted 2017-01-03T08:50:00.077

Reputation: 7 772

I don't know Jelly, but could you save a byte by increasing N before you generate the range? – Emigna – 2017-01-03T09:21:19.833

@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, ...]. – steenbergh – 2017-01-03T09:25:40.483

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. – Emigna – 2017-01-03T09:28:23.817

5

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

Brad Gilbert b2gills

Posted 2017-01-03T08:50:00.077

Reputation: 12 713

4

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.

xnor

Posted 2017-01-03T08:50:00.077

Reputation: 115 687

3

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

rahnema1

Posted 2017-01-03T08:50:00.077

Reputation: 5 435

3

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

Mego

Posted 2017-01-03T08:50:00.077

Reputation: 32 998

3

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!

flawr

Posted 2017-01-03T08:50:00.077

Reputation: 40 560

3

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.

Adám

Posted 2017-01-03T08:50:00.077

Reputation: 37 779

3

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;

Arthur Shveida

Posted 2017-01-03T08:50:00.077

Reputation: 141

3IIRC, the <? doesn't have to be part of your byte count (because PHP has a command-line mode that doesn't require it). – None – 2017-01-03T10:55:18.507

3The old trick: compare against <1 instead of ==0. – manatwork – 2017-01-03T11:19:24.407

Dang. I reached to for(;!($argv[1]%$i);$i++);echo$i;. Yours is the natural evolution of mine. This has my upvote! – Ismael Miguel – 2017-01-05T19:00:32.657

3

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]

steenbergh

Posted 2017-01-03T08:50:00.077

Reputation: 7 772

3

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.

user48543

Posted 2017-01-03T08:50:00.077

Reputation:

I2/L/);?%<@O for a couple of bytes less. Same general process, just different path – MickyT – 2018-01-30T20:28:48.463

2

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

Sok

Posted 2017-01-03T08:50:00.077

Reputation: 5 592

2

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.

Zgarb

Posted 2017-01-03T08:50:00.077

Reputation: 39 083

2

Pyke, 5 bytes

1D.f%

Try it here!

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

Blue

Posted 2017-01-03T08:50:00.077

Reputation: 26 661

2

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

M L

Posted 2017-01-03T08:50:00.077

Reputation: 2 865

2

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

Addison Crump

Posted 2017-01-03T08:50:00.077

Reputation: 10 763

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? – Kevin Cruijssen – 2017-03-24T08:35:46.987

@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. – Addison Crump – 2017-03-27T18:08:53.390

2

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

cmaster - reinstate monica

Posted 2017-01-03T08:50:00.077

Reputation: 381

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. – Robert Benson – 2017-01-05T19:24:36.040

@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... – cmaster - reinstate monica – 2017-01-06T09:35:35.557

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. – Robert Benson – 2017-01-07T02:16:40.367

2

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

Timtech

Posted 2017-01-03T08:50:00.077

Reputation: 12 038

Ans is not an allowed I/O method. – Mego – 2017-01-09T18:47:45.440

According to who? – Timtech – 2017-01-09T18:50:34.163

That didn't work when I tested with 24. – kamoroso94 – 2018-01-30T16:47:25.957

@kamoroso94 Thanks for pointing that out, I had mistakenly put I/Ans instead of Ans/I but it's fixed now. – Timtech – 2018-01-31T04:11:54.300

2

Japt, 5 bytes

@uX}a

Try it here

Shaggy

Posted 2017-01-03T08:50:00.077

Reputation: 24 623

2

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.

histocrat

Posted 2017-01-03T08:50:00.077

Reputation: 20 600

1

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.

James Holderness

Posted 2017-01-03T08:50:00.077

Reputation: 8 298

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) – MildlyMilquetoast – 2017-01-03T19:01:12.987

1

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

Taylor Scott

Posted 2017-01-03T08:50:00.077

Reputation: 6 709

1Save 1 byte by deleting the space between [A1] and mod – Engineer Toast – 2018-01-30T19:03:29.290

1

MATL, 6 bytes

t:\f1)

Try it online!

James

Posted 2017-01-03T08:50:00.077

Reputation: 54 537

You need Q after t so that it works for inputs 1 and 2 – Luis Mendo – 2017-01-04T01:11:18.077

1

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

peech

Posted 2017-01-03T08:50:00.077

Reputation: 309

@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. – Post Rock Garf Hunter – 2017-01-04T04:27:26.120

247 bytes: int n(int x){int y=1;for(;x%++y==0;);return y;} – Addison Crump – 2017-01-04T10:13:59.837

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). – Addison Crump – 2017-01-04T10:20:14.250

@peech You can use my solution in the comment two above this, you know. ;) Shaves off another two bytes. – Addison Crump – 2017-01-04T16:17:47.940

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 – 2017-01-05T12:31:19.840

@peech My solution isn't significantly different enough to post it separately. :P Please, use it. – Addison Crump – 2017-01-05T20:27:16.533

hehe ok, thank u very much :) – peech – 2017-01-06T09:49:53.410

1instead i==0 write i<1 – user902383 – 2017-01-07T13:12:29.087

1

Clojure, 48 Bytes

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

Nahuel Greco

Posted 2017-01-03T08:50:00.077

Reputation: 111

1

PowerShell, 26 bytes

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

Try it online!

briantist

Posted 2017-01-03T08:50:00.077

Reputation: 3 110

1Other solutions have switched from !() to <1, would that help here too? – Neil – 2017-01-03T19:51:05.733

2@Neil powershell uses bash-style operators, so it would end up being -lt1 (or -eq0), one byte longer unfortunately. – briantist – 2017-01-03T20:43:45.563

1

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.

FryAmTheEggman

Posted 2017-01-03T08:50:00.077

Reputation: 16 206

1

Japt, 8 bytes

U%°V?V:ß

This was inspired by Arnauld's solution.

Thanks ETHproductions for golfing this even more!

Try it Online!

Oliver

Posted 2017-01-03T08:50:00.077

Reputation: 7 160

1I 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 – 2017-01-03T23:36:53.097

@ETHproductions Wow, very nice! – Oliver – 2017-01-04T01:04:36.630

1

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.

Mitchell Spector

Posted 2017-01-03T08:50:00.077

Reputation: 3 392

1

REXX, 35 bytes

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

idrougge

Posted 2017-01-03T08:50:00.077

Reputation: 641

1

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.

Robert Benson

Posted 2017-01-03T08:50:00.077

Reputation: 1 339

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. – Christian Sievers – 2017-01-05T00:29:42.963

Good catch. I can fix it by adding 4 bytes :( – Robert Benson – 2017-01-05T19:13:37.913

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. – Christian Sievers – 2017-01-06T00:27:54.237

@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 – Robert Benson – 2017-01-07T02:24:40.327

I feel you. ;-) – Christian Sievers – 2017-01-07T03:16:33.830

1

Ruby, 28 bytes

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

Alexis Andersen

Posted 2017-01-03T08:50:00.077

Reputation: 591

@GB yep, my bad. I foobed in the golfing stage. – Alexis Andersen – 2017-01-05T14:59:01.570

1

Perl, 25 bytes

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

Gregory Nisbet

Posted 2017-01-03T08:50:00.077

Reputation: 111

1

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.

Rohan Jhunjhunwala

Posted 2017-01-03T08:50:00.077

Reputation: 2 569

1

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.

Martin Ender

Posted 2017-01-03T08:50:00.077

Reputation: 184 808

1

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.

12Me21

Posted 2017-01-03T08:50:00.077

Reputation: 6 110

1

Emojicode, 74 bytes

➡️i 10ii➕1ii

Try it online!

betseg

Posted 2017-01-03T08:50:00.077

Reputation: 8 493

1

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

reffu

Posted 2017-01-03T08:50:00.077

Reputation: 1 361

1

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)

Kevin Cruijssen

Posted 2017-01-03T08:50:00.077

Reputation: 67 575

0

C 70 bytes

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

Abel Tom

Posted 2017-01-03T08:50:00.077

Reputation: 1 150

0

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

rnso

Posted 2017-01-03T08:50:00.077

Reputation: 1 635

0

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

Mitchell Spector

Posted 2017-01-03T08:50:00.077

Reputation: 3 392

(($1%($2)))&&bc<<<$2||$0 $1 $2+1 to be run as scriptname N 2 – izabera – 2017-01-07T07:35:07.923

@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. – Mitchell Spector – 2017-01-07T18:04:54.853

0

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.

Neil

Posted 2017-01-03T08:50:00.077

Reputation: 95 035

0

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.

M L

Posted 2017-01-03T08:50:00.077

Reputation: 2 865

0

FALSE, 32 bytes

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

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

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

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

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

Explanation:

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

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

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

Try it out here.

M L

Posted 2017-01-03T08:50:00.077

Reputation: 2 865

You can remove the function definition/call entirely: 1[\$@$@$@$@\/*-0=][1+]#. to get 24 bytes. (insert the value to test at the beginning) – 12Me21 – 2018-01-30T15:39:32.430

0

Matlab, 45 Bytes

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

Owen Morgan

Posted 2017-01-03T08:50:00.077

Reputation: 221

0

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

Addison Crump

Posted 2017-01-03T08:50:00.077

Reputation: 10 763

0

Java 8, 37 bytes

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

user902383

Posted 2017-01-03T08:50:00.077

Reputation: 1 360

0

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.

Dan Getz

Posted 2017-01-03T08:50:00.077

Reputation: 533

0

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

jyoti proy

Posted 2017-01-03T08:50:00.077

Reputation: 101

2You 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.) – None – 2017-01-05T08:12:03.667

0

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.

Adam J

Posted 2017-01-03T08:50:00.077

Reputation: 81

0

GameMaker Language, 58 bytes

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

Timtech

Posted 2017-01-03T08:50:00.077

Reputation: 12 038

0

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

Carcigenicate

Posted 2017-01-03T08:50:00.077

Reputation: 3 295

0

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

12Me21

Posted 2017-01-03T08:50:00.077

Reputation: 6 110

0

C (gcc) 30 bytes

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

Try it online!

PrincePolka

Posted 2017-01-03T08:50:00.077

Reputation: 653

0

Julia 0.6, 25 bytes

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

Try it online!

gggg

Posted 2017-01-03T08:50:00.077

Reputation: 1 715

0

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

caird coinheringaahing

Posted 2017-01-03T08:50:00.077

Reputation: 13 702

0

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

Comrade SparklePony

Posted 2017-01-03T08:50:00.077

Reputation: 5 784

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.

Jo King

Posted 2017-01-03T08:50:00.077

Reputation: 38 234

0

SNOBOL4 (CSNOBOL4), 57 bytes

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

Try it online!

Giuseppe

Posted 2017-01-03T08:50:00.077

Reputation: 21 077

0

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!

ATaco

Posted 2017-01-03T08:50:00.077

Reputation: 7 898

0

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!

mudkip201

Posted 2017-01-03T08:50:00.077

Reputation: 833

0

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.

rpgwaiter

Posted 2017-01-03T08:50:00.077

Reputation: 1

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

– Mr. Xcoder – 2018-01-31T18:09:38.180

0

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

user85052

Posted 2017-01-03T08:50:00.077

Reputation:

0

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

Kevin Cruijssen

Posted 2017-01-03T08:50:00.077

Reputation: 67 575

1@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. :) – Kevin Cruijssen – 2020-01-22T14:07:16.653

0

Perl 6, 13 bytes

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

Try it online!

Jo King

Posted 2017-01-03T08:50:00.077

Reputation: 38 234