59
\$\begingroup\$

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>

\$\endgroup\$
2
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Jan 6, 2017 at 0:05
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Commented Jan 31, 2018 at 4:41

100 Answers 100

1 2 3
4
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

SNOBOL4 (CSNOBOL4), 57 bytes

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

Try it online!

\$\endgroup\$
0
\$\begingroup\$

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!

\$\endgroup\$
0
\$\begingroup\$

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!

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
1
  • 1
    \$\begingroup\$ @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. :) \$\endgroup\$ Commented Jan 22, 2020 at 14:07
0
\$\begingroup\$

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
```
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ 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 :) \$\endgroup\$
    – Mr. Xcoder
    Commented Jan 31, 2018 at 18:09
0
\$\begingroup\$

Perl 5 -p, 15 bytes

1until$_%++$\}{

Try it online!

\$\endgroup\$
0
\$\begingroup\$

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.
\$\endgroup\$
0
\$\begingroup\$

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!

\$\endgroup\$
13
  • \$\begingroup\$ 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). \$\endgroup\$
    – Aiden Chow
    Commented Aug 18, 2023 at 22:18
  • \$\begingroup\$ 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. \$\endgroup\$
    – Aiden Chow
    Commented Aug 18, 2023 at 22:21
  • \$\begingroup\$ @Aiden Chow oh, i just directly set \$a\$ to the entire action instead \$\endgroup\$
    – fwoosh
    Commented Aug 18, 2023 at 22:22
  • \$\begingroup\$ You would need a leading newline in your "expression list" unless you swap the two lines. \$\endgroup\$
    – Aiden Chow
    Commented Aug 18, 2023 at 22:23
  • \$\begingroup\$ Hmmm, I can still paste it without the newline \$\endgroup\$
    – fwoosh
    Commented Aug 18, 2023 at 22:25
1 2 3
4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.