text:
The program that will find the next prime number
Intro:

You accidentally corrupted the flow of time with a device you made for fun, that turned out to be a time machine. As a result, you got pushed to the far future. You  realized that computing, processing power, and computers in general have been evolved by a huge amount, an infinite amount to be precise. So you grab yourself a computer with infinite memory and processing power. You have no idea how it can have infinite memory and infinite processing power, but you just accept it and return to the present.
Challenge:

You heard that the person who discovered the currently largest prime 2^74,207,281 − 1 got paid $100.000. You decide to make a program that finds the next prime, since you want to get back the money you spent for the computer. You make one that takes input of a number, and finds the next prime number, either by bruteforcing or any other method.
Clarifications:
You have a hypothetical machine with infinite memory and processing power. Your program MUST NOT be limited (e.g.: C#'s int's can store from -2,147,483,648 to 2,147,483,647), well your program must be able to store, and work with any number of any size. You have infinite resources, so you shouldnt care if you would run out of memory if you allowed that.
Example I/O:
Input: The currently largest discovered prime with 22,338,618 digits.
Output: Exactly the next prime
Obviously, you dont have to prove that it works, as it would take a ton of time to compute in a physical machine. But if you moved your program to a hypothetical machine with infinite processing power / memory, it should compute instantly.

Finding the next prime and checking if a number is a prime, are two completely different things

Does it have to specifically be the next prime? Lots of prime searching algorithms for large primes only search certain types of numbers and therefore sometimes miss out primes...

Yes it has to be exactly the next prime @FlipTack. Not the next mersenne prime or anything. This is why I advised bruteforcing, (due to infinite resources, it would be ideal) but any algorithm is fine, as long as it finds the next prime.

Does the program have to validate that the input is actually a prime? Or can we just get the next prime after any input?

@theonlygusti It doesnt have to validate inputs primality.

I think you should add some serious test cases.

"Your program MUST NOT be limited" but on the basis of the example I suspect that every single language in existence counts as limited if fit no other reason than using a finite type to address memory.

Side note: there isn't a $100,000 bounty for every new world-record prime—only a few benchmarks, like the first prime found with a million digits. See mersenne.org

Weird, there's not a single Lisp answer to this question...

How is this different from the primality test question?  Any reasonable method is just going to be a fairly simple wrapper of the original or a builtin.

How would this be tested anyway? No machines have infinite resources.

Downvoting because I don't get the point of the challenge. Is it about finding the next prime number (trivial, and it has been done before) or manipulating large numbers in the context of prime number searching? It looks like none of the answers actually adresses this latter issue (which looks like the interestingone to me) - maybe because the question is unclear

If there were a machine with infinite processing power and memory it could instantly calculate the next prime with any program that actually works. There would no point in making programs either small or efficient any more, indeed, I suspect that in such a universe computers would be so cheap that I'd have better things to do than try to recoup the cost of one. I assume this is the case in your example, where a stick of gum may cost $100,000. I'd probably just ask a nearby computer to project all the great entertainment I missed into my mind before I notice my family have all died.

Possible duplicate of Is this number a prime?

@WheatWizard No way. Finding the next prime is different.

@mbomb007 why? All of the answers except the builtin ones seen to just add an extra wrapper.

So does pretty much any question tagged with [prime].

For all the "wtf there isnt any biggest prime number"-esque edits, the title obviously meant "next currently known biggest prime number so your sarcasm is not valid here :)

Mathematica, 9 bytes
NextPrime

... Does this actually work?

Of course, Mathematica always has a builtin

@wizzwizz4, sure, Try it online!

Python 3, 45 bytes
f=lambda n,k=1,m=1:m%k*k>n or-~f(n,k+1,m*k*k)

Try it online!

I believe this is Wilson's Theorem in disguise. k is equal to the final result, m contains (k-1)!^2. Since (k-1)! = -1 mod k only holds when k is prime, we have (k-1)!(k-1)! = 1 mod k, which when multiplied by k will be k itself. You calculate the square to get rid of the only exception of (k-1)! = 0 mod k for composite k, which occurs for k = 4. Correct?

Yes, that is correct.

This throws RecursionError: maximum recursion depth exceeded in comparison for f(1000)

@ovs The question says we have infinite memory. Therefore we can assume an infinitely high recursion depth limit, and thus not worry about RecursionError.

Python 2, 78 77 76 74 bytes
def f(n):
 while 1:
    n+=1
    if[i for i in range(1,n)if n%i<1]==[1]:return n

-1 byte thanks to @KritixiLithos
-1 byte thanks to @FlipTack
-2 bytes thanks to @ElPedro

n%i<1 is shorter than n%i==0

You don't need whitespace after that if.

I think you mean <1

I think you can use a tab instead of 2 spaces for the second level indents but I can't test at the moment.

@ElPedro is right. You can change the 2 spaces in front of n+=1 and if into tabs and save 2 bytes

Sorry @ovs. I'm still predominantly Python 2 so wasn't aware of that. Will remember for next time :-)

67 bytes by using all(..)instead of the list comprehension.

Regex  (PCRE2 v10.35 or later), 80 77 bytes
^(?=(?*(x+?)(x*$))(?!(?*(xx+)(x+$))(?=\3*(x+))(?=\4\5(x*))\6\2\3*$))\2x+|\B|$

Attempt This Online!
Takes its input in unary, as a string of x characters whose length represents the number. Returns its output as the number of ways the regex can match. (The rabbit emoji indicates this output method.)
This is the first -regex I've written that can be really said to compute its result before turning it into a number of possible matches. This output method allows actually directly returning the result; before adopting this output method, it was impossible for a regex to return a value greater than the input.
The regex computes \$p-n\$, where \$n\$ is the input and \$p\$ is the next prime. To do this it takes advantage of the fact that there will always be a prime in the interval \$(n,2n]\$. Once that is complete, it outputs \$p-n+n=p\$ in the form of a number of possible matches.
    ^                    # tail = N = input number
    (?=
        (?*              # Non-atomic lookahead (try all options until matching)
            (x+?)(x*$)   # \1 = conjectured P - N; \2 = N - \1
        )
        (?!              # Negative lookahead - assert that this cannot match
            (?*          # Non-atomic lookahead (try all options until matching)
                (xx+)    # \3 = try all numbers from 2 through N-1
                (x+$)    # \4 = N - \3; assert \3 < N
            )
            (?=          # Atomic lookahead (locks onto the first match)
                \3*(x+)  # \5 = N % \3, giving \3 instead of 0
            )
            (?=          # Atomic lookahead (locks onto the first match)
                \4       # head = \4
                \5       # head += \5
                (x*)     # \6 = tail == N - head == tool to make tail = \4 + \5
            )
            \6           # tail = tail-\6 == \4 + \5
            \2           # tail -= \2
            \3*$         # Assert tail is divisible by \3
        )
    )
    \2                   # tail = \1
    x+                   # add tail to the number of possible matches
|
    \B                   # add abs(N-1) to the number of possible matches
|
    $                    # add 1 to the number of the possible matches; this gets
                         # us a return value of 2 for N==0, instead of 0 which we
                         # would have if simply adding N instead of abs(N-1)+1

Molecular lookahead (?*...) is used for convenience. It would be possible to port to flavors that don't have it, but the regex would be much longer – it would still need to emulate arithmetic in the range \$[0,2n]\$, but would need to do so within just \$[0,n/4]\$ or perhaps \$[0,n/3]\$, instead of \$[0,n]\$ as this version does.
Without returning the correct value for \$0\$, this would be 72 bytes.
Regex  (.NET), 79 bytes
(?=(x)*)((?<1>x)+?)(x*$)(?<!(?=(?=\6*(x+))\5\4(?<=^\3\6*))(^x+)(x+x))|(?<1>){2}

Try it online!
Returns its output as the capture count of group \1.
                           # tail = N = input number
    (?=(x)*)               # \1.captureCount = N
    ((?<1>x)+?)(x*$)       # Assert N > 0; \2 = P - N;
                           # \1.captureCount += \2; \3 = N - \2
    (?<!                   # Right-to-left negative lookbehind
        (?=                # Atomic lookahead
            (?=            # Atomic lookahead
                \6*(x+)    # \4 = N % \6, giving \6 instead of 0
            )
            \5             # head = \5
            \4             # head += \4
            (?<=           # Right-to-left atomic lookbehind
                ^\3\6*     # Assert head-\3, that is, \5+\4-\3, is divisible by \6
            )
        )
        (^x+)              # \5 = N - \6; assert \6 < N
        (x+x)              # \6 = try all numbers from 2 through N-1
    )
|
    (?<1>){2}              # if N == 0, \1.captureCount = 2

Without returning a value for \$0\$, this would be 69 bytes.

What do the emojis mean?

@Bbrk24 Except for rabbit, they're animals documented to be able to count. Bee is output via number of matches, because counting that is fairly lightweight to implement in most languages (bees are small). Elephant is output via capture count, because that is in a way kind of overkill (elephants are big), since in .NET a capture stack contains the contents of its captures, which is potentially much more information than just the number of captures. Rabbit `` is output via number of ways it can match, because rabbits multiply (breed), and this output method is great at multiplying.

@Bbrk24 The reason I use emojis for those output methods is to differentiate them from output via the length of a string. Depending on the challenge, it can be a very different, or sometimes even impossible, to output via the length of a string instead of the count of something. Trivially it's impossible to output a number larger than the input without using a counting-style output, but also there are ones like totient function in ECMAScript where it's much more complicated and interesting to output via string length than some type of count.

Interesting, thanks!

Jelly, 2 bytes
Æn

Try it online!
This implicitly takes input z and, according to the manual, generate the closest prime strictly greater than z.

Oasis, 2 bytes
Run with the -n flag.
Code:
p

Try it online!

Bash + coreutils, 52 bytes
for((n=$1,n++;`factor $n|wc -w`-2;n++)){ :;};echo $n

Try it online!
The documentation for bash and factor do not specify a maximum integer value they can handle (although, in practice, each implementation does have a maximum integer value).  Presumably, in the GNU of the future on your infinitely large machines, bash and factor will have unlimited size integers.

Actually the docs do specify for factor that if built without gnu mp only single-precision is supported.

@Dani_l Well, the man entry for bash only says: "Evaluation is done in fixed-width integers with no check for overflow, though division by 0 is trapped and flagged as an error." It doesn't specify the width. (As I recall, the stock implementations of bash on my machines use 64-bit signed integers, but I can't check right now.) As for factor, it will surely be updated: the OP's future computers with infinite resources will have factor compiled with gnu_up to get unlimited precision :).

Maxima, 10 bytes
next_prime

A function returns the smallest prime bigger than its argument.

Python with sympy, 28 bytes
import sympy
sympy.nextprime

sympy.nextprime is a function which does what it says on the tin. Works for all floats.
repl.it

Python, 66 59 bytes
-4 bytes thanks to Lynn (use -~)
-3 bytes thanks to FlipTack (use and and or, allowing ...==1 to be switched to a ...-1 condition.)
f=lambda n:sum(-~n%-~i<1for i in range(n))-1and f(n+1)or-~n

repl.it
A recursive function that counts up from n until a prime is found by testing that only one number exists up to n-1 that divides it (i.e. 1). Works for all integers, raises an error for floats.
Works on 2.7.8 and 3.5.2, does not work on 3.3.3 (syntax error due to lack of space between ==1 and else)

(n+1)%(i+1) is -~n%-~i, I think.

It is, thanks... I was trying to do a  shorter one using Wilson's theorem.

Does short circuiting and/or work, such as f=lambda n:sum(-~n%-~i<1for i in range(n))==1and-~n or f(n+1)?

In fact, that ^ can be golfed to f=lambda n:sum(-~n%-~i<1for i in range(n))-1and f(n+1)or-~n

@FlipTack I originally avoided them so it could pass through zero, but it'll work - that's a three byte save!

f= is unnecessary. Just like the first solution, omitting f= will make the program return a function which does what you need.

@Makonede Full programs cannot "return a function" they only return an exit code. Regardless the second function here is recursive and so the f(n+1) will need f to be a reference to this same function and so f= is necessary (even if full-programs could somehow do what you suggest).

Ah good point. However, an issue here is that the one using sympy does in fact return a callable function, which, when run, will do what is expected. I think you're contradicting yourself here.

@Makonede No contradiction, the requirements of a function on this site are just that it be reusable later in code and that it fulfils the specification in the question. Both of these happen to be named functions, the second only needs to be named so it can reference itself.

Brachylog, 2 bytes
<ṗ

Try it online!
Explanation
(?) <   (.)      Input < Output
      ṗ (.)      Output is prime
                 (Implicit labelization of the Output at the end of the predicate)

Pyke, 8 7 bytes
~p#Q>)h

Try it here!
4 bytes, noncompeting
(Interpreter updated since challenge posted)
~p<h

Try it here!
~p   -   primes_iterator()
  <  -  filter(^, input() < i)
   h - ^[0]

Why's the second noncompeting? I don't understand enough.

@theonlygusti: Typically, the only legitimate reason to mark a submission noncompeting here (as opposed to not submitting it at all) is because you fixed a bug or added a feature in the language the program's written in, and that helped you with the challenge. (I tend to write it as "language postdates challenge" to be more clear.)

@theonlygusti clarified

Python, 114 83 bytes
def g(b):
 while 1:
  b+=1
  for i in range(2,b):
   if b%i<1:break
  else:return b

Without builtins, if there are any.
-30 by removing whitespace and -1 by changing b%i==0 to b%i<1

This won't find the next prime if you put in 1

It now assumes that b>2

You can't just make up your own rules... you need to follow the challenge specification. Nowhere does it say that you can assume the bounds of the input.

Even with that assumption, this fails for all even valued inputs.

I'm an idiot, i misread it. Fixed it. @FlipTack

you can use spaces for single indents and tabs for double indents to save bytes

Perl 6, 25 bytes
{first *.is-prime,$_^..*}

How it works
{                       }  # A lambda.
                  $_ ..*   # Range from the lambda argument to infinity,
                    ^      # not including the start point.
 first           ,         # Iterate the range and return the first number which
       *.is-prime          # is prime.

Perl 6, 32 bytes
{first {all $_ X%2..^$_},$_^..*}

With inefficient custom primality testing.
How it works
Outer structure is the same as above, but the predicate passed to first (to decide if a given number is prime), is now:
{               }  # A lambda.
     $_            # Lambda argument (number to be tested).
          2..^$_   # Range from 2 to the argument, excluding the end-point.
        X          # Cartesian product of the two,
         %         # with the modulo operator applied to each pair.
 all               # Return True if all the modulo results are truthy (i.e. non-0).

I was hoping to get something shorter with Perl 5 but it's hard to beat a built-in .is-prime ;)

Lua, 876 Bytes
function I(a)a.s=a.s:gsub("(%d)(9*)$",function(n,k)return tostring(tonumber(n)+1)..("0"):rep(#k)end)end function D(a)a.s=a.s:gsub("(%d)(0*)$",function(n,k)return tostring(tonumber(n)-1)..("9"):rep(#k)end):gsub("^0+(%d)","%1")end function m(a,b)local A=K(a)local B=K(b)while V(0,B)do D(A)D(B)end return A end function M(a,b)local A=K(a)local B=K(b)while V(m(B,1),A)do A=m(A,B)end return A end function l(n)return#n.s end function p(a)local A=K(a)local i=K(2)while V(i,A)do if V(M(A,i),1)then return false end I(i)end return true end function V(b,a)A=K(a)B=K(b)if l(A)>l(B)then return true end if l(B)>l(A)then return false end for i=1,l(A)do c=A.s:sub(i,i)j=B.s:sub(i,i)if c>j then return true elseif c<j then return false end end return false end function K(n)if(type(n)=='table')then return{s=n.s}end return{s=tostring(n)}end P=K(io.read("*n"))repeat I(P)until p(P)print(P.s)

Lua, unlike some other languages, does have a Maximum Integer Size. Once a number gets larger than 232, things stop working correctly, and Lua starts trying to make estimates instead of exact values.
As such, I had to implement a new method of storing numbers, in particular, I've stored them as Base10 strings, because Lua doesn't have a size limit on Strings, other than the size of the memory.
I feel this answer is much more to the Spirit of the question, as it has to itself implement arbitrary precision integers, as well as a prime test.
Explained
-- String Math
_num = {}

_num.__index = _num

-- Increase a by one.
-- This works by grabbing ([0-9])999...$ from the string.
-- Then, increases the first digit in that match, and changes all the nines to zero.
-- "13", only the "3" is matched, and it increases to 1.
-- "19", firstly the 1 is turned to a 2, and then the 9 is changed to a 0.
-- "9" however, the 9 is the last digit matched, so it changes to "10"
function _num.inc(a)
    a.str = a.str:gsub("(%d)(9*)$",function(num,nines)
            return tostring(tonumber(num)+1)..("0"):rep(#nines)
        end)
end

-- Decrease a by one
-- Much like inc, however, uses ([0-9])0...$ instead.
-- Decrements ([0-9]) by one and sets 0... to 9...
-- "13" only the "3" is matched, and it decreases by one.
-- "10", the "1" is matched by the ([0-9]), and the 0 is matched by the 0..., which gives 09, which is clipped to 9.
function _num.dec(a)
    a.str = a.str:gsub("(%d)(0*)$",function(num,zeros)
        return tostring(tonumber(num)-1)..("9"):rep(#zeros)
    end)         :gsub("^0+(%d)","%1")
end

-- Adds a and b
-- Makes A and B, so that the original values aren't modified.
-- B is then decremented until it hits 0, and A is incremented.
-- A is then returned.
function _num.__add(a,b)
    local A = str_num(a)
    local B = str_num(b)
    while B > 0 do
        A:inc()
        B:dec()
    end
    return A
end

-- Subs b from a
-- Works just like Addition, yet Dec's A instead of Incs.
function _num.__sub(a,b)
    local A = str_num(a)
    local B = str_num(b)
    while B > 0 do
        A:dec()
        B:dec()
    end
    return A
end

-- A % B
-- Makes A and B from a and b
-- Constantly subtracts B from A until A is less than B
function _num.__mod(a,b)
    local A = str_num(a)
    local B = str_num(b)
    while A >= B do
        A = A - B
    end
    return A
end

-- #a
-- Useful for golfiness
function _num.__len(n)
    return #n.str
end

-- Primacy Testing
-- Generates A from a and i from 2.
-- Whilst i is less than A, i is incremented by one, and if A % i == 0, then it's not a prime, and we return false.
-- Once that finishes, we return true.
function _num.isprime(a)
    local A = str_num(a)
    local i = str_num(2)
    while i < A do
        if A%i < 1 then
            return false
        end
        i:inc()
    end
    return true
end

-- b < a
-- A and B are generated from a and b
-- Fristly, if the length of A and B aren't equal, then that result is output.
-- Otherwise, each character is searched from left to right, the moment they are unequal, the difference is output.
-- If all the characters match, then it's equal. Return false.
function _num.__lt(b,a)
    A=str_num(a)
    B=str_num(b)
    if #A > #B then
        return true
    end
    if #B > #A then
        return false
    end
    for i=1, #A.str do
        As = A.str:sub(i,i)
        Bs = B.str:sub(i,i)
        if As > Bs then
            return true
        elseif As < Bs then
            return false
        end
    end
    return false
end

-- b <= a
-- Same as b < a, but returns true on equality.
function _num.__le(b,a)
    A=str_num(a)
    B=str_num(b)
    if #A > #B then
        return true
    end
    if #B > #A then
        return false
    end
    for i=1, #A.str do
        As = A.str:sub(i,i)
        Bs = B.str:sub(i,i)
        if As > Bs then
            return true
        elseif As < Bs then
            return false
        end
    end
    return true
end

-- Just straight up returns it's string component. Endlessly faster than the int equivalent, mostly because it never is anything _but_ the string form.
function _num.__tostring(a)
    return a.str
end

-- Just set up the metatable...
function str_num(n)
    if(type(n)=='table')then
        return setmetatable({str = n.str}, _num)
    end
    return setmetatable({str = tostring(n)}, _num)
end

-- Generate a new str_num from STDIN
Prime = str_num(io.read("*n"))

-- This is handy, because it will call Prime:inc() atleast once, and stop at the next prime number it finds.
-- Basically, if it weren't for all that overhead of making the math possible, that's all this would be.
repeat
    Prime:inc()
until Prime:isprime()
print(Prime)

Although the above uses Metatables, instead of just regular functions like the actual answer, which worked out smaller.

Vyxal, 2 bytes
∆Ṗ

Try it Online!
Here for completeness. Like answers in many other golfing langs, ∆Ṗ is simply a builtin for "next prime greater than n". It uses sympy.nextprime from Python's sympy library to do this

J, 4 bytes
4&p:

Simple built in for next prime.

05AB1E, 16 13 bytes (Emigna @ -3 bytes)
2•7£?ÿ•o[>Dp#

Try it online!
2•7£?ÿ•o        # Push current largest prime.
        [   #    # Until true..
         >Dp    # Increment by 1, store, check primality.
                # After infinite loop, implicitly return next prime.

Wouldn't [>Dp# work?

You can still cut 8 more bytes as the program should take a prime as input and output the next prime.

@Emigna then this question is a duplicate.

That is probable yes.

Java 7, 373 343 334 303 268 bytes
import java.math.*;class M{public static void main(String[]a){BigInteger n,i,o,r=new BigInteger(a[0]);for(r=r.add(o=r.ONE);;r=r.add(o)){for(n=r,i=o.add(o);i.compareTo(n)<0;n=n.mod(i).compareTo(o)<0?r.ZERO:n,i=i.add(o));if(n.compareTo(o)>0)break;}System.out.print(r);}}

-75 bytes thanks @Poke
Ungolfed:
import java.math.*;
class M{
  public static void main(String[] a){
    BigInteger n,
               i,
               o,
               r = new BigInteger(a[0]);
    for(r = r.add(o = r.ONE); ; r = r.add(o)){
      for(n = r, i = o.add(o); i.compareTo(n) < 0; n = n.mod(i).compareTo(o)< 0
                                                        ? r.ZERO
                                                        : n,
                                                   i = i.add(o));
      if(n.compareTo(o) > 0){
        break;
      }
    }
    System.out.print(r);
  }
}

Try it here.
Some example input/outputs:
7 -> 11
1609 -> 1613
104723 -> 104729

@Poke I've golfed another 31 bytes by adding static for the field and method p, but removing method c and p's parameter.

Perl, 30 bytes (29 +1 for -p):
(1x++$_)=~/^(11+?)\1+$/&&redo

Usage
Input the number after pressing return (input 12345 in example below, outputs 12347):
$ perl -pe '(1x++$_)=~/^(11+?)\1+$/&&redo'
12345
12347

How it works

Define a string of 1's that has length ++$_, where $_ is initially the input value
The regex checks to see if the string of 1s is non-prime length (explained here).
If the string length is non-prime, the check is re-evaluated for the next integer (++$_)
If the string length is prime, the implicit while loop exits and -p prints the value of $_
Note: there is no need to handle the edge case "1" of length 1 because it will never be used for values less than 1, per the specification.

05AB1E, 2 bytes
ÅN

Try it online!
ÅN  # full program
ÅN  # push smallest prime greater than...
    # implicit input
    # implicit output

Pyth, 5 bytes
fP_Th

Try it online!

Explanation:
f      # first integer greater than or equal to
    hQ # input + 1
 P_T   # which is prime

Husk, 4 3 bytes
Edit: -1 byte thanks to Leo
ḟṗ→

Try it online!
ḟ     # first element that
 ṗ    # is a prime,
  →   # counting up beginning at one greater than the input

ḟ can take a number rather than a list as second argument, and count up from that https://tio.run/##yygtzv7//@GO@Q93Tn/UNun///@GBgaWAA

@Leo - Thanks!  I really should have read the manual...

Java, 176 Bytes
import java.math.*;import java.util.*;class a{public static void main(String[] args){System.out.print(new BigInteger(new Scanner(System.in).nextLine()).nextProbablePrime());}}

Welcome to the site and nice first answer! Be sure to check out our Tips for golfing in Java

@ChartZBelatedly thanks! that was very helpful!

Vyxal, 40 bits1, 5 bytes
{›:æ¬|

Try it Online!
Non-built-in answer, but does use a prime check built-in
Explained
{›:æ¬|
{    | # While
 ›     # incrementing the top of the stack
  :æ¬  # gives a non prime number:
       #  do nothing. just run the condition actually.

Vyxal, 52 bits1, 6.5 bytes
{›:KḢ₃¬|

Try it Online!
Uses KḢ₃ as a prime check (len(factors(x)[1:] == 1)

Nekomata -1, 3 bytes
Ƥ$>

Attempt This Online!
Explanation
Ƥ$>  # Implicit input
Ƥ    # Find the first prime
  >  # which is greater than
 $   # the input integer
     # Implicit output

Thunno 2, 3 bytes
µƘP

Try it online!
Explanation
µƘP  # Implicit input
µƘ   # Find the next number after the input
  P  # which is a prime number
     # Implicit output

QBIC, 34 bytes
:{a=a+1[2,a/2|~a%b=0|b=a]]~a<b|_Xa

Based off this QBIC primality tester. Explanation:
:{a=a+1    Read 'a' from the command line, start an infinite loop
           and at the start of each iteration increment 'a'
[2,a/2|    FOR b = 2, b <= a/2, b++
~a%b=0|    IF b cleanly divides a, we're no prime
b=a]]      so, break out of the FOR loop ( ]] = End if, NEXT )
~a<b|      If the FOR loop completed without breaking
_Xa        then quit, printing the currently tested (prime) number
           The second IF and the DO-loop are implicitly closed by QBIC.

JavaScript (ES7), 61 bytes
a=>{for(;a++;){for(c=0,b=2;b<a;b++)a%b||c++;if(!c)return a;}}

Usage
f=a=>{for(;a++;){for(c=0,b=2;b<a;b++)a%b||c++;if(!c)return a;}}
f(2)

Output
3

Nice, but I don't think this will work, as JavaScript itself (not the computer) will lose precision after just 2^53.

You're right, but I don't think that limit can be avoided, even if we split the number up in portions of 32 bits in an array, because eventually, the number needs to be processed as a whole. If you do have an idea on how to solve this, please let me know.

There are JS libraries for arbitrary-precision math--I even built one at some point--so I'm certain it's possible. I'll have a go the next time I'm at my computer

I did some googling, and it seems interesting. I'll have a shot at it too.

MATL, 3 bytes
_Yq

The function Yq returns the next prime of the absolute value of the input if the input is negative so we implicitly grab the input, negate it (_) and find the next prime using Yq.
Try it Online!

Haskell, 42 46 43 bytes
f n=[i|i<-[n..],all((>0).rem i)[2..i-1]]!!1

the usual code for brute force.
Of course this finds the next smallest prime number after n. There is no biggest prime.
Works for n > 0.
edit: Assumes n is prime. Thanks to @Laikoni's advice in the comments.

You can save a byte by replacing head[...] with [...]!!0. However I think one can assume that n is prime, so you can use [n..] instead of [n+1..] and then take the second element with [...]!!1.

Ruby, 28+6 = 34 bytes
Uses the -rprime flag.
f=->i{i+=1;i.prime??i :f[i]}

Non-recursive version for 31+6=37 bytes:
->i{i+=1;i+=1 while i.prime?;i}

SimpleTemplate, 132 bytes
The algorithm is terrible, since I have to do my own code to check if a number is prime or not.
It proved to be horrible, but works.
{@setY argv.0}{@setX 1}{@whileX}{@setX}{@set+T Y,-1}{@for_ from2 toT}{@ifY is multiple_}{@incX}{@/}{@/}{@ifX}{@incY}{@/}{@/}{@echoY}

Receives the number as the first argument, outputting the result.

Ungolfed:
{@set number argv.0}
{@set remainder 1}
{@while remainder}
    {@set remainder 0}
    {@set+ tmp number, -1}
    {@for divisor from 2 to tmp}
        {@if number is multiple divisor}
            {@inc by 1 remainder}
        {@/}
    {@/}
    {@if remainder}
        {@inc by 1 number}
    {@/}
{@/}
{@echo number}

Any tips on how to remove that last @if?

Python + primefac, 34 32 bytes
Not quite as short as using sympy (another answer already uses that), but it's still pretty short, and it's much faster.
import primefac as p
p.nextprime

Try it online
Input of 2**2000 completes in a couple seconds.

Japt, 6 bytes
_j}aUÄ

Run it online.


text:
Kolmogorov Complexity Meta Golfer

Mike Bufardeci (Pyth) - 175 bytes

Leo (Retina) - 175 bytes

devRicher (Lua) - 182 bytes

Peter Taylor (CJam) - Waiting for clarification

Lyth (C++11) - Waiting for clarification

Edit: Several changes made, should not affect any already submitted answers.
Edit #2: Very few people are taking advantage of the 1024 byte limit. The point of this challenge is to output code golf answers, not things like the example at the bottom of this post.
Edit #3: Here is the paragraph to test against: WASHINGTON - These are chaotic and anxious days inside the National Security Council, the traditional center of management for a president's dealings with an uncertain world. I will test the submissions myself later.
At PPCG, we pride ourselves in writing programs to solve problems. However, it's very time consuming to write the programs to solve problems. Instead we should write programs to write programs to solve problems!
In this case, the problem is Kolmogorov Complexity. You must write a program that golfs a program, that outputs piece of text.
Main program -> Generated program -> Text
You do not necessarily need to golf the main program. Your score is the length of the generated program.

You will not know the final text when writing the main program. Therefore, you will not be able to write the generated program by hand. The main program should take a string input and create the generated program, which correctly outputs the text.

On February 12th, the first paragraph of the headline of the New York Times will be used for scoring. I will post the article at 10 AM ESThttps://www.nytimes.com/

You may use any language for the main program and generated program. They do not have to be the same.

The final text will never contain these characters: ", ', \n, \r.

The main program is limited to 1024 bytes (not characters). The generated program has no byte limit, as long as it outputs the text.

Compression algorithms built in to your language are not allowed (both ways), unless you code it from scratch. This includes any type of text compression libraries, and base conversion. This does not include Regexes.

Standard loopholes apply.

Example: (JavaScript)
f=(g)=>{console.log("console.log('" + g + "')")}

Compression algorithms built in to your language are not allowed That's fuzzy. What qualifies as compression algorithm? Things like run-length decoding are probably borderline

The code is expected to run in a reasonable amount of time. That's unenforceable. What's reasonable?

In order for this challenge to be objective you must lock in your choice of text right now, before revealing it, by posting a hash of it. Otherwise you have 100% free reign in choosing the winner by choosing a text that best matches your chosen answer.

So the main challenge is to compress an unknown string, and the score is determined by the resulting program?

@Dennis, e.g. The code does not take hours to run. Mainly so it can't be a brute force a hash solution.

@orlp I have chosen the text, but I don't think there is a fair way to prove I chose it in advance. If you have a suggestion, I would appreciate it.

@devRicher Yes.

So I do not know my score until you publish the string?

@devRicher This is clearly stated in the challenge: "In two weeks, I will post what text I have chosen. "

@JulianLachniet Yes there is, if you publish the hash of the text you chose right now we know when you post the text later that it's the correct text that you chose now.

@JulianLachniet If you want an even stronger guarantee, you can instead post a function that generates a text given a number, and state that the number used to generate the scoring text will be the hash of the headline of a big publicly available newspaper at a certain date. This way no one knows the text ahead of time, including you.

Also, why is the main program restricted to 512 bytes? It makes any attempt of making your own compression algorithm (since pre-made ones are invalid) a lot harder in common languages.

@orlp I will try that.

@devRicher Because you could just paste in the code of a built in. Trough I agree that the 512 bytes should be more.

@devRicher 512 might be too small. But, it is necessary to have done cutoff. I will change it to 1024

It seems that none of the people who have voted to put this question on hold have explained their reason to do so. To me, the only unclear restriction seems to be "The code is expected to run in a reasonable amount of time" - and I think it's debatable if this is too unclear.
As such, I'm voting to reopen.

@Leo Let me explain then. What is considered a built in compression algorithm? A posted answer uses a built in to do base conversion on the string, does that count?

I really like this challenge and think there shouldn't be a winning criterion and that the objective should be to create one in every language.

@carusocomputing One of the rules of this site is that all challenges need an objective winning criterion.

@MikeBufardeci yes, I am familiar with the rules, but there are multiple posts that say the goal is not to find the shortest answer in a language, rather the shortest answer in all languages. These posts are usually on the more interesting side.

@carusocomputing That's the nature of all code golf questions. The golfscript answers compete with the other golfscript answers, the java answers compete with the other java answers, etc. That wouldn't really work with this scoring criteria however.

@MikeBufardeci I'm talking more along the lines of [tag:popularity-contest].

Let us continue this discussion in chat.

As @JulianLachniet stated in chat, using built in base conversion is not allowed.

"paragraph of the headline"? How long will it approximately be?

@smls here is an example: WASHINGTON — As President Trump signed a sweeping executive order on Friday, shutting the borders to refugees and others from seven largely Muslim countries, the secretary of homeland security was on a White House conference call getting his first full briefing on the global shift in policy.

Okay, wait, so hold the #@%! up. Can I at least use a built-in to DECOMPRESS? Like, can I generate code that uses a built in but the code to generate the code doesn't use the built-in?

@JulianLachniet Make sure to include any rule changes and clarifications in your challenge description.

What are "Reflexes"? 2. How are you able to guarantee that an unwritten paragraph in an English-language newspaper "will never contain these characters: ", ', ..."?

@PeterTaylor typo

When you say "Compression algorithms built in to your language are not allowed (both ways)", do you mean built-in compression and decompression are not allowed?

Can the input contain backslashes? Or non-ASCII characters?

Also, is it okay if the main program takes a few minutes to run?

@MikeBufardeci Yes.

@smls Of course.

@JulianLachniet I am confused: you have two seemingly contradictory statements: You do not necessarily need to golf the main program. Your score is the length of the generated program. and The main program is limited to 1024 bytes (not characters). The generated program has no byte limit, as long as it outputs the text. What is the reason for the limit on the main program if we are scored on the generated program?

I ask because non-trival answers that perform a compression process via main program and decompression via generated program are penalized by having to effectively store both compression and decompression processes within the 1024 byte limit... but are scored only on the size of the generated program that contains only the decompression process

@Moogle The point of the byte limit is to prevent copying and pasting large compression algorithms. Without it, your code could be infinitely long. As for your second question, that is really the point of the challenge.

@JulianLachniet Ok, If that is the intention then that is fine. I do, however think unless the input text that will be output by the generated file is significantly larger than one paragraph then the trivial answers will always win it is very unlikely that the ~100 or so bytes saved via a decent compression alg will not offset the cost of implementing the decompresor alg. But i will like to be proven incorrect :-)

Couldn't you just have a few long strings (e.g. ~10 paragraphs from NY times on the day of posting this challenge) as the testcases instead of this "I'll post the message in the future" stuff?

@Qwerp-Derp If I posted the test cases, you would be able to bias your code to work better on the test cases. By not giving the text in advance, you have to try to objectively write a text compressor.

@JulianLachniet But given a big enough "pool" of test-cases, it's nearly impossible to optimise for the test case at all, simply because there's too much to optimise for. It doesn't necessarily have to be 10 paragraphs - a bigger sample size (e.g. maybe 50-100 paragraphs) is almost guaranteed to eliminate any bias.

@Qwerp-Derp That is true, but this is easier than finding 100 paragraphs about different subjects.

@JulianLachniet It's already possible to bias the code to work better for this challenge than in general. Many assumptions can be made about next Sunday's NY times article. It will likely start with "WASHINGTON – " and contain the phrase "President Trump" at least once. Each of those words will probably appear again in the article.

I'm a bit sad that the testing paragraph is so short :(
Anyway, is that "Nationalional" a typo? @JulianLachniet

"Paragraph"? That's just a sentence

@Kritixi_Lithos It's both. I would choose a different paragraph, but someone would accuse me of being biased by not following my own rules.

@PeterTaylor Your code doesn't seem to work for me. What environment are you using?

@Lyth I am unable to run the code on my computer. What environment are you using?

I'm voting to close this question because the secret string has now been revealed, meaning that one can no longer post answers to the original challenge of compressing an unknown string.

Retina, worst case (3+original length) bytes
EDIT: added support for newlines, in order to try this code in actual kolmogorov complexity challenges. Behaviour on strings without newlines remains unchanged.
Retina is great at substituting substrings, so that's what we're going to do!
This program looks for repeated sequences of characters and replaces them every time with a single character not appearing in the full string. The generated program then starts with the "compressed" string and applies all substitutions in reverse.
This code adds 3 bytes of boilerplate (a newline at the beginning, and a \` towards the end to suppress a trailing newline), so in the worst case (when there are no repeated sequences worth substituting) we have a length of 3 bytes more than the starting string. On average, this will shave a few bytes from the original length, not much but still a compression.
Here's the code with some comments:
First, we use a trick with transliteration ranges to change newlines into ¶, which is how newlines are printed in a Retina program
T`µ¶·`µ-·

then we start the main loop, duplicating the first line
{`^.+
$&¶$&

we only substitute when the sequence is repeated enough times (depending on its length)
^.*?((......+).*?\2|(.....?).*?\3.*?\3|(...).*?\4.*?\4.*?\4|(..).*?\5.*?\5.*?\5.*?\5.*?\5).*
"$2$3$4$5
^"(.+)|^.*
$+

to find a character not in the string, we append a list of candidates to the string, using " as separator, and then remove duplicates
^(.*)¶(.*)
$2" 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!#%&\'()*+,-./:;?@\^_`{|}~¶$2¶$1
D`(?<=^.*).
^.*"(.)?.*¶(.+)
$2¶$1

here the actual substitution in the text happens
+`^(.*)(.+)(.*¶(.)¶\2(¶|$))
$1$4$3

in case we couldn't find a repeated sequence or an unused character, we restore the string to the original state (which makes us break from the loop)
}`(.*)¶(¶.*|.*¶)(¶|$)
$1$3

at the end, we add the 3 bytes of boilerplate
^
¶
\-1=`.*¶
\`$&

Try it online!
In the linked example, the 292 bytes paragraph gets compressed to a 286 bytes Retina code.
NOTE: the substitutions made are not optimal, we just make every time the first suitable substitution we find; I don't know if an algorithm finding the optimal substitutions could run in a reasonable amount of time.

Pyth, worst case length(input) + 1 bytes
=kNJ++kzkV92Iq/zC+32N0 aYC+32N))V.:z7I>/JN2=J+++\::JNK.)Y+\\K++kNk))V.:z6I>/JN2=J+++\::JN=K.)Y+\\K++kNk))V.:z5I>/JN2=J+++\::JN=K.)Y+\\K++kNk))V.:z4I>/JN3=J+++\::JN=K.)Y+\\K++kNk))V.:z3I>/JN4=J+++\::JN=K.)Y+\\K++kNk))V.:z2I>/JN7=J+++\::JN=K.)Y+\\K++kNk))?qeJkPJJ

Test Suite Available Online
Generated Programs from Test Suite
Explanation
This program no longer abuses the fact that the article will be the first paragraph of a NY Times article and is now a general compressor of short strings. There are still some assumptions being made here, specifically that not all characters will appear in the text and that the text is at least seven characters long.
The high level explanation is that the program searches thorough the text for progressively shorter repeated strings, then replaces each repeated with a character not present in the text. Each string length has its own break even point where making a substitution is actually shorter than leaving the text alone. For strings of length 7 only 2 occurrences are needed but for strings of length 3 the break even point is 4 occurrences.
Main Program
The main program mostly consists of six loops: one each for strings of length seven down through strings of length 2. Each loop goes over all substrings of the input with that length, counts how often they appear in the article and determines if a replacement should be made. If a replacement is made then the string is wrapped with a replacement method to obtain the original string.
This breakdown is itself broken down into several parts for readability. This first part is setting up for the main loops.
=kNJ++kzkV95Iq/zC+32N0 aYC+32N))
  N                               N is initialized to " (the double quote character)
=kN                               assign " to k
       z                          z is initialized to the input
    ++kzk                         wrap z with double quotes
   J                              and assign that to J (J automatically assigns on first use)
          92     +32      +32     32-126 is the "printable" character range
          92     +32      +32     | causes issues so we stop before it (code point 124)
         V92                   )  for each printable character:
              /zC+32N              count occurrences of it in the input
            Iq       0        )    if there are 0 occurrences:
                       aYC+32N      append that character to list Y (Y is initialized to an empty list)

The six main loops are nearly identical. I will breakdown a general loop for the sake of simplicity.
V.:z5I>/JN2=J+++\::JN=K.)Y+\\K++kNk))
   z                                   z is the input
 .:z5                                  get each substring of a certain length (here 5)
V                                   )  for each string:
       /JN                              count how many times it appears in the input
     I>   2                        )    if count > break even point: (here 2)
                       .)Y               pop a character off Y (unused characters list)
                     =K                  assign it to K (K automatically assigns the first time but must be manually assigned after that)
                  :JN K                  regex replacement:
                   J                      in the input
                    N                     replace current string
                      K                   with popped character
               +\:                       prepend : (the colon character)
              +           +\\K           append \ and popped character
             +                ++kNk      append current string wrapped in double quotes
           =J                            and assign to variable J

This last section only saves one byte on the generated program but also ensures that the worst case is as long as our trivial answer.
?qeJkPJJ
    k     k is still set to " (the double quote character)
   J  JJ  J is the string to be returned
?qeJk     if the last character of J is ":
     PJ    return J without the last character
          else:
       J   return J

Generated Program
If no substitutions are made the generated program will be in this format:
"(input)

This will have a length of length(input) + 1 bytes. This is the worst case, and I fear it may also be the average case. One paragraph does not have a lot of repeated strings, especially because professional writers try to vary their words.
If one substitution is made then the generated program will be in this format:
:"(input with replacements)"\(unused character)"(replacement string)

In Pyth, this is the format for replacement with regular expressions. Instances of the unused character in the input are replaced with the replacement string.
This adds a static 6 characters to the string, but in the worst case we are hitting the break even point mentioned earlier.
Here is the format for a generated program with two replacements:
::"(input with replacements)"\(char 1)"(str 1)"\(char 2)"(str 2)

As replacements stack up we simply add another colon to the front and add the substring and replacement character to the end.
I have not determined what the size reduction is in the best case. If anyone can determine the size of the generated program in the best case please let me know.

CJam, Burrows-Wheeler transform and run-length encoding
I think it's stupid to ban builtins for base-conversion as "compression", but I've implemented my own, as well as implementing run-length encoding and decoding manually rather than using the builtin.
q
e# Reduce range, add start-of-message marker
[0\:i_:e<(:If-+
e# Burrows-Wheeler transform
_,({_(+}*]$Wf=
e# RLE without e`, decrementing each runlength for compactness
0\{_2$={;\)}0?\}%\;2/
e# Pair [runlength-1 ch] to a single int
_1f=:e>):Paf{.*1b}
e# Base-convert to the minimal possible base
_:e>):B;W%{\B*+}*
e# Base-convert to base 256
[{256md\}h;]W%
e# Format as a string literal with as few special cases as possible
:c'"\'"/"\\\""*'"
e# Decoder base-converts to base 256, then base B, unpairs, run-length decodes, and
e# inverse Burrows-Wheeler transforms
":i{\256*+}*{"B"md"P"mda\)*\}h;]e_:A,Ma*_,{A\.+$}*0=(;"I"cf+"

I is the increment which must be added to each decoded value
P is the base used to combine run-length with char
B is the base used to convert the whole thing

CJam, range reduction and base conversion
I think it's stupid to ban builtins for base-conversion as "compression", but I've implemented my own.
q
e# Reduce range by offsetting towards 0 as far as possible
:i_:e<:If-
e# Base-convert to the minimal possible base
_:e>):B;W%{\B*+}*
e# Base-convert to base 256
[{256md\}h;]W%
e# Format as a string literal with as few special cases as possible
:c'"\'"/"\\\""*'"
e# Decoder base-converts to base 256 and then base B, adding the offset
":i{\256*+}*{"B"md"I"c+\}h;"

The text is too small to benefit greatly from techniques which require a lot of decoding, but if we can subtract 32 from each byte and base-convert then we get an asymptotic improvement of at least 2.4%, and with luck the input source will be pure ASCII and we get an asymptotic improvement of about 18.7%. With an overhead of about 26 bytes we stand a decent chance of getting compression.
If the output is allowed to have a trailing NUL byte, one byte can be saved by removing that final ;.

This is not a valid answer: Compression algorithms built in to your language are not allowed (both ways), unless you code it from scratch. This includes any type of text compression libraries, and base conversion. This does not include Regexes.

@JulianLachniet, it's a perfectly valid answer. "unless you code it from scratch".

If you are coding it from scratch, that's fine. Your post does not make that clear.

@JulianLachniet, I thought my other answer made it pretty clear, but as you insist I've copied across the relevant introduction.

Pyth, length(input) + 1 bytes
+Nz

Online interpreter available here.
This will return a generated program of the form "(input). Put another way, the main program prepends a double quote to the input text.
Main Program Explanation
+      Concatenate
 N     " (the variable N defaults to a double quote mark)
  z    and the input

Generated Program Explanation
"                start of a string
 (input)         the input text
        (eof)    strings are closed automatically at the end of file

This is the shortest of the "input length plus a constant" answers. I'm posting this mostly to set a bar for the non-trivial answers. It's unclear if a non-trivial answer can exist within the rules as they are currently worded, but I am setting this bar nonetheless.

Submissions should attempt to be competitive. There is already a trivial answer, and to me, there shouldn't be any. "Try to optimize your score" http://meta.codegolf.stackexchange.com/a/7076/34718

Let us continue this discussion in chat.

C++11, arithmetic coding, overhead >= 382 bytes
Compression algorithm is shamelessly copied from Simple byte-aligned binary arithmetic coder by Fabian 'ryg' Giesen
#include <iostream>
using std::cout;
void pu(char c){c=='\r'?cout.write(")OMG\" \"\\r\" R\"OMG(",17):cout.put(c);}

int main() {
    uint32_t lo{0},hi{~0u},x,i,prob{256};
    char ch;

    cout<<R"!*(#include <iostream>
void operator ""_p(const char* q,size_t z){uint32_t d{0},l{0},h{~0u},p{256},x,t;size_t r{0},i;for(i=4;i-->0;)d=(d<<8)|q[r++];while(r<=z){char y{0};for(i=8;i-->0;){x=l+((uint64_t(h-l)*p)>>9);t=(d<=x);t?(h=x):(l=x+1);while((l^h)<(1u<<24)){d=(d<<8)|q[r++];l<<=8;h=(h<<8)|0xff;}p+=t?((512-p)>>5):-(p>>5);y+=y+t;}std::cout.put(y);}}int main(){R"OMG()!*";

    while (std::cin.get(ch)) {
        for (size_t b=8; b-->0;) {
            int bit{ch&(1<<b)};
            x = lo+((uint64_t(hi-lo)*prob)>>9);
            bit ? (hi=x) : (lo=x+1);
            while ((lo^hi)<(1u<<24)) {pu(lo>>24);lo<<=8;hi=(hi<<8)|0xff;}
            prob += bit?((512-prob)>>5):-(prob>>5);
        }
    }
    for (i=4;i-->0;) {pu(lo>>24);lo<<=8;}
    cout<<")OMG\"_p;return 0;}";

    return 0;
}

Explanation

Main program reads the input and uses BinShiftModel to generate an encoded bitstream.
The bitstream is then included into a C++11 user-defined raw literal in the output program.
The literal is being processed by the user-defined function, operator ""_p(const char* string, size_t size), printing out the decoded stream.

Some extra care was necessary due to all newline values being converted to \n.
Improvement
The code does not look for different compression paths (there were, but some optimal value was chosen instead).
It is possible to improve the compression ratio, either by limiting input to 7 bits (did not do that because "em-dash" in the sample became corrupted) or by storing MSB from all input bytes first, which will likely be roughly same for 1/4 of the text.
Either way, algorithm overhead is huge on small texts.
Usage
g++ -std=c++11 -o golf golf.cpp && ./golf < sample.txt > degolf.cpp && g++ -std=c++11 -o degolf degolf.cpp && ./degolf

As implemented this is actually an adaptives binary arithmetic coder because it doesn't track the partially coded byte (you would need 255 different probs to achieve byte order). This usally doesn't work very well at all for text (probably 1-2%). A byte oriented coder would give you around 1/3 reduction rate for english text.

@Christoph you're right. I do not expect byte-oriented coder to fit into 1024 bytes with decoder, though.

There are only a few minor changes which probably pay of quite fast: prob would have to be an array of 256 elements and used as prob[ctx] (problem maybe to init it all to 256 but changing math to use prob[ctx] as prob[ctx]+256 and init to 0 should do the trick). ctx would be set to 1 at the start of each byte and gets shifted in the coded bit ctx = (ctx << 1) |bit; after each bit.

Lua
print('print"'..io.read()..'"')

Try it here.
Will always be string length + 7 bytes long.
C#
using System;
namespace H {
    class K {
        static string P;
        static void Main(string text)
        {
            P = text;
            Console.WriteLine("()=>{Console.WriteLine(H.K.P);}");
        }
    }
}

Works if the program itself is added as a dependency where you run the resulting output program. If you would to run the resulting code in a OutputText.exe, you will have to add OutputCodeThatOutputsText.exe as a dependency.
Resulting code is always ()=>{Console.WriteLine(H.K.P)}.

source: Stack Exchange

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

sort: votes


text:
Filesystem-sort my directory please
Sometimes lexicographical sorting of strings may cut it, but when browsing the filesystem, you really need better sorting criteria than just ASCII indices all the time.
For this challenge, given a list of strings representing filenames and folders in a directory, do a filesystem sort, explained below:

Split every string into an array of alternating digits (0123456789) and non-digits. If the filename begins with digits, insert an empty string at the beginning of the array.
For each element in the array, if the element is a string, lexicographically sort all the strings by that element in all lowercase or uppercase. If the element is a number, sort by numerical order. If any files are tied, continue to the next element for more specific sorting criteria.

Here is an example, starting with strings that are initially sorted lexicographically:
Abcd.txt
Cat05.jpg
Meme00.jpeg
abc.txt
cat.png
cat02.jpg
cat1.jpeg
meme03-02.jpg
meme03-1.jpeg
meme04.jpg

After step 1, you'll get this:
"Abcd.txt"
"Cat", 5, ".jpg"
"Meme", 0, ".jpeg"
"abc.txt"
"cat.png"
"cat", 2, ".jpg"
"cat", 1, ".jpeg"
"meme", 3, "-", 2, ".jpg"
"meme", 3, "-", 1, ".jpeg"
"meme", 4, ".jpg"

After step 2, you'll get this:
abc.txt
Abcd.txt
cat1.jpeg
cat02.jpg
Cat05.jpg
cat.png
Meme00.jpeg
meme03-1.jpeg
meme03-02.jpg
meme04.jpg

Here are the rules:

You may not assume the list of input strings is sorted in any order
You may assume that the input strings only contain printable ASCII characters
You may assume that when the filenames are converted to all lowercase or all uppercase, there will be no duplicates (i.e., a case-insensitive filesystem)
Input and output may be specified via any approved default method
Standard loopholes apply

Here is an example implementation of the sorting algorithm if there is any confusion:
function sort(array) {
  function split(file) {
    return file.split(/(\D*)(\d*)/);
  }

  return array.sort((a, b) => {
    var c = split(a);
    var d = split(b);

    for (var i = 0; i < Math.min(c.length, d.length); i++) {
      var e = c[i].toLowerCase();
      var f = d[i].toLowerCase();

      if (e-f) {
        return e-f;
      }

      if (e.localeCompare(f) !== 0) {
        return e.localeCompare(f);
      }
    }

    return c.length - d.length;
  });
}

This is code-golf, so shortest answer wins!

Jelly, 26 bytes
VµŒlµœ&ØDµ?
e€ØDI0;œṗ⁸Ç€µÞ

Try it online! (The footer code, ÇY, just splits the resulting list of strings with line feeds for legibility)
How?
VµŒlµœ&ØDµ? - Link 1, evaluate a substring: substring
 µ  µ    µ? - ... then / else / if ...
       ØD   - if:   decimal digit characters '0123456789'
     œ&     -       multi-set intersection, effectively "all digits"?
V           - then: eval, cast the digit strings to integers
  Œl        - else: convert to lowercase, cast the char strings to lowercase

e€ØDI0;œṗ⁸Ç€µÞ - Main link: list of filenames
            µ  - monadic chain separation
             Þ - sort the filenames by the key function, given a single filename:
  ØD           - decimal digit character yield, '0123456789'
e€             - exists in for €ach -> a list of 0s at chars and 1s at digits
    I          - increments -> 1s and -1s at changeover indexes - 1, 0s elsewhere, 0s
     0;        - prepend a zero -> 1s and -1s at changeover indexes, 0s elsewhere
         ⁸     - left argument, the filename
       œṗ      - partition at the truthy indexes (the 1s and -1s)
          Ç€   - call the last link (1) as a monad for €ach substring

Bean, 116 121 118 bytes
Hexdump:
00000000 26 55 cd a0 62 80 40 a0 6f 53 d0 80 d3 d0 80 a0  &UÍ b.@ oSÐ.ÓÐ.
00000010 6f 20 80 0d 21 80 81 00 20 80 92 20 6f 53 d0 80  o ..!... .. oSÐ.
00000020 a0 78 20 80 83 40 a0 5d a0 5e 53 d0 80 d3 a0 62   x ..@ ] ^SÐ.Ó b
00000030 20 5d 20 80 8b 40 a0 5f a0 60 a0 65 a0 6e dd a0   ] ..@ _ ` e nÝ
00000040 61 50 84 d3 a0 62 20 5e 20 65 4e ce a0 5f 80 4c  aP.Ó b ^ eNÎ _.L
00000050 a0 60 8c 20 61 80 53 d0 80 d3 50 80 a0 60 20 80   `. a.SÐ.ÓP. ` .
00000060 b9 20 80 b3 53 50 80 a0 61 20 80 b9 a8 dc c4 aa  ¹ .³SP. a .¹¨ÜÄª
00000070 a9 a8 dc e4 aa 29                                ©¨Üäª)
00000076

Equivalent JavaScript (140 bytes, ignoring added whitespace for formatting):
f=s=>s.split(/(\D*)(\d*)/).concat(s),
_.sort(
  (a,b)=>f(a).reduce(
    (c,d,i,r,e=f(b)[i])=>
      c||d-e||d.toLowerCase().localeCompare(e.toLowerCase())
  )
)

Basically a golfed version of the example implementation given in the question.
Click here for the demo!

Nice to see a new language! ^^

JavaScript (ES6), 105 110 101 97 82 bytes
Assumes that each numeric element is up to 99 characters long.
a=>a.sort((a,b)=>(F=s=>s.toLowerCase().replace(/\d+/g,n=>n.padStart(99)))(a)>F(b))

Test

let f =

a=>a.sort((a,b)=>(F=s=>s.toLowerCase().replace(/\d+/g,n=>n.padStart(99)))(a)>F(b))

console.log(f([
  'Abcd.txt',
  'Cat05.jpg',
  'Meme00.jpeg',
  'abc.txt',
  'cat.png',
  'cat1.jpeg',
  'cat02.jpg',
  'meme03-1.jpeg',
  'meme03-02.jpg',
  'meme04.jpg'
]).join('\n'))

Weird... I wouldn't have thought of a solution like this. I know I never stated to assume strings would have less than a certain amount of characters, but I guess this is valid. Nice job

I'm confused why you're changing it when the previous (smaller) solution was acceptable

@PatrickRoberts The previous version failed to compare files such as [ 'abc', 'cat', 'abcd' ]. Only numeric elements should be padded with zeros.

Good catch, I'll add that to the test case

Nit: padStart, although widely supported (and therefore legal), isn't part of ES6, is it?

@Neil Indeed. It's still just a proposal.

Perl 6,  50 45  44 bytes
*.sort:{.lc~~/(\D*)*%%$0=(\d+)/;map {+$_//~$_},@0}

Try it
*.sort:{/(\D*)*%%$0=(\d+)/;map {+$_//.lc},@0}

Try it
*.sort:{/(\D*)*%$0=(\d+)/;map {+$_//.lc},@0}

Try it
Expanded:
* # Whatever lambda ( this is the argument )

.sort: # sort by doing the following to each value

{  # bare block lambda with implicit parameter ｢$_｣
  /
    (      # stored in $0
      \D*                  # any number of non-digits
    )*                     # any number of times
    %                      # separated by
    $0 = ( # stored in $0
      \d+                  # at least one digit
    )
  /;

  map {
    +$_    # try to turn the element into a number
    //     # if that fails
    .lc    # lowercase it
  },
  @0       # for all the elements
}

JavaScript (ES2020), 54 bytes
a=>a.sort(new Intl.Collator('en',{numeric:1}).compare)

Uses the Intl.Collator builtin to provide the natural sort order.
Test

const f =

a=>a.sort(new Intl.Collator('en',{numeric:1}).compare)

console.log(f([
  'Abcd.txt',
  'Cat05.jpg',
  'Meme00.jpeg',
  'abc.txt',
  'cat.png',
  'cat1.jpeg',
  'cat02.jpg',
  'meme03-1.jpeg',
  'meme03-02.jpg',
  'meme04.jpg'
]))

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

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


text:
Give me your tired, your poor, Your huddled masses yearning to breathe free
A bronze plaque in the pedestal of the Statue of Liberty displays the poem "The New Colossus" by Emma Lazarus, part of which reads:

Give me your tired, your poor,
  Your huddled masses yearning to breathe free,
  The wretched refuse of your teeming shore.
  Send these, the homeless, tempest-tost to me,
  I lift my lamp beside the golden door!

To simplify this section of the poem for this challenge, we'll make it all uppercase and replace the newlines with slashes (/), keeping commas and other punctuation as is:
GIVE ME YOUR TIRED, YOUR POOR,/YOUR HUDDLED MASSES YEARNING TO BREATHE FREE,/THE WRETCHED REFUSE OF YOUR TEEMING SHORE./SEND THESE, THE HOMELESS, TEMPEST-TOST TO ME,/I LIFT MY LAMP BESIDE THE GOLDEN DOOR!

We'll call this string S. It has md5 hash 8c66bbb9684f591c34751661ce9b5cea. You may optionally assume it has a trailing newline, in which case the md5 hash is 0928ff6581bc207d0938b193321f16e6.
Write a program or function that takes in a single string. When the string is S, output in order, one per line, the six phrases that describe the type of people the poem depicts Lady Liberty asking for:
TIRED
POOR
HUDDLED MASSES YEARNING TO BREATHE FREE
WRETCHED REFUSE OF YOUR TEEMING SHORE
HOMELESS
TEMPEST-TOST

(This precise string, optionally followed by a single trailing newline, must be your output for input S.)
For at least one input string that is not S, your output should be any string other than the six lines above. This could be as simple as outputting only TIRED if the input is only GIVE ME YOUR TIRED. This rule is to prevent pure hardcoding. Otherwise, when the input string is not S, your code may do anything.
This is essentially a constant-output challenge where you are given an input that is relatively close to the output. You could of course mostly ignore the input and hardcode the output, but it may be better to, say, strip out the substrings of the input needed for the output.
For reference, here are the zero-based indices and lengths of the six output lines in S:
13 5, 25 4, 36 39, 81 37, 136 8, 146 12

The shortest code in bytes wins.

According to the rules, it seems like we can simply output the input when it's not equal to S. Is that correct?

That is a valid option, yes.

Does it matter whether the output is an actual single string with newlines vs the program outputting an array of lines, which on the console will be indistinguishable from the string?

I don't think the hardcoding ban was needed because hardcoding is too long.

@briantist That sounds ok.

Do we have to qualify it by country of origin?

So, instead of hardcoding a string, we can do input&&hardcoded ? That's not that limiting.

So, to clarify- it's acceptable to return the six phrases back even when we aren't given S, as long as there exists an input that doesn't return the six phrases?

@Delioth Correct

Jelly, 19 bytes
Ẇ“©ØḌKAƑ⁶2ɼU’b8ȷ¤ịY

Try it online! or try it with some other text.
How?
Indexes into the list of all non-empty contiguous slices of the input string and joins with line feeds.
Ẇ“©ØḌKAƑ⁶2ɼU’b8ȷ¤ịY - Main link: s
                ¤   - nilad followed by link(s) as a nilad
 “©ØḌKAƑ⁶2ɼU’       - base 250 number, 27003436588466956354336
              8ȷ    - 8 * 1e3 = 8000
             b      - convert to base, [824,635,7086,6796,1544,2336]
                 ị  - index into
Ẇ                   - all non-empty contiguous slices of s
                  Y - join with line feeds

Previous code, 22 bytes:
“ÇŒȷœ%LRw⁹ƊƓɠ‘ṬœṗµḊm2Y

Partitions the input string, takes every second element and joins with line feeds. “ÇŒȷœ%LRw⁹ƊƓɠ‘ is a list of code page indexes, Ṭ makes a list of zeros with ones at those indexes, œṗ partitions the input at the truthy indexes of that list, Ḋ removes the first element, m2 takes every second element, and Y joins with line feeds.

JavaScript (ES6), 128 69 bytes
May output empty lines or some garbage when the input is different from S.

let f =

s=>[837,1604,2343,5221,8712,9356].map(n=>s.substr(n>>6,n&63)).join`
`

console.log(f(`GIVE ME YOUR TIRED, YOUR POOR,
YOUR HUDDLED MASSES YEARNING TO BREATHE FREE,
THE WRETCHED REFUSE OF YOUR TEEMING SHORE.
SEND THESE, THE HOMELESS, TEMPEST-TOST TO ME,
I LIFT MY LAMP BESIDE THE GOLDEN DOOR!`))

console.log(f(`THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG`))

Bash, 76 65 60 bytes
echo "TIRED
POOR
${1:36:39}
${1:81:37}
HOMELESS
${1:146:12}"

Try it online!

Mathematica, 71
Column@StringTake[#,List@@@{14|18,26|29,37|75,82|118,137|144,147|158}]&

PowerShell, 72 bytes
"$args"-split'[/,.]'-replace'^.*?(YOUR|\bTHE) |^ | TO ME'-match'^[^S G]'

Try it online!
Explanation
This is a pretty crappy regex solution.
Splitting the string into an array on / or . or , and then replacing parts of each string that match the first pattern, which gives an array of -replaced strings, then use the -match operator to return an array of the elements that match the second pattern (which gets rid of the blank lines and 2 lines that didn't get filtered before).

Mathematica, 86 bytes
Riffle[s=#;s~Take~#&/@{{14,18},{26,29},{37,75},{82,118},{137,144},{147,158}},"
"]<>""&

Unnamed function taking a list of characters as input and returning a string. Just extracts the relevant substrings of the input and concatenates with newlines.

My input format is not a String but a list of Characters.

Retina, 38 32 bytes
It can probably be improved, but this is a job for regexes!
!`(?<=R |HE ).*?(?=[,.])|\w+-\w+

Try it online!

TI-Basic, 58 bytes
Very straightforward. Disp is like println, so there are newlines in between.
Disp "TIRED","POOR",sub(Ans,37,39),sub(Ans,82,37),"HOMELESS",sub(Ans,147,12


text:
Parse the Markdown-like Markup!
The Challenge
In this challenge, you are supposed to write a program or function that takes in a String, which will contain the simplified Markdown-like Markup, and outputs the corresponding HTML Markup.

The Input
You can take input in whatever way you wish to. The type of the input should be String.

The Output
You can output the result in any way you want. Logging to Console or Terminal, printing on screen, returning from function etc. are perfectly valid.

The Rules

Convert each occurrence of *foo* and _foo_ to foo.
Convert each occurrence of **foo** and __foo__ to foo.
Convert each occurrence of <tab or four spaces here>foo\n to
foo
.
Convert each occurrence of #foo\n to
foo
.
Convert each occurrence of ##bar\n to
bar
.
Convert each occurrence of ###bar\n to
bar
.
Convert each occurrence of ####bar\n to
bar
.
Convert each occurrence of #####bar\n to
bar
.
Convert each occurrence of ######bar\n to
bar
.
Convert each occurrence of [foo](https:\\www.bar.com) to foo.
Convert each occurrence of ![foo](https:\\www.bar.com) to .
Convert each occurrence of >foo\n to
foo
.
Convert each occurrence of - foo\n as
foo
 (add
 before the li if the - is the first of its consecutive series and add
 if it is the last.)
Convert each occurrence of n. foo\n (where the first n denotes an Integer such as 12,1729 etc.) as
foo
 (add
 before the li if the element is the first of its consecutive series and add
 if it is the last.)
Although there exist many more rules of conversion, you are supposed to follow only the abovementioned ones (for the sake of simplicity).
You are supposed to output only the corresponding HTML Markup for the given String. No need to add extra elements that are necessary for creating a valid HTML file (like ,  etc.). However, if they are present in the input String, then you will have to output them too, that is, replace < and > with < and >, repspectively.
You must NOT use any built-in! (I doubt whether there exists one)

Note : In the abovementioned rules, foo, bar and https:\\www.bar.com are only placeholders. Your program or function must be flexible enough to work for Strings different than these too.

Scoring
This is code-golf, so the shortest code in bytes wins!

Test Cases
"**Hello**" -> "Hello"

"#IsThisAwesome?\n" -> "
IsThisAwesome?
"

">![Image](http:\\www.somewhereontheinternet.com) -> "

"

">Some Content\n- Item1\n- Item2\n- Item3\n" -> "
Some Content

Item1

Item2

Item3

"

"1.Hello\n2.Bye\n3.OK\n" -> "

Hello

Bye

OK

"

Special Thanks to FakeRainBrigand!
This challenge was originally proposed by @FakeRainBrigand in the Sandbox. He granted me the permission to post this challenge on the regular website. Due to unclear and broad specifications, the challenge was closed. Now, it has been reopened with clearer and fewer specs by @Arjun.

Good point. I removed that from the post.

It would be nice to have a more rigorous specification for each rule.  For instance I notice that your ordered list input are not numbers 1-3 while the result is.  It would be nice to know exactly what is required.

I didn't write this challenge but thanks for the feedback

I vote to close as unclear what you're asking because there are at least 500 unexplained corner cases. Markdown is an incredibly tricky language that everyone has some idea of what it 'should look like', but a formal specification is quite long. This is nowhere near a complete specification.

@orlp If you read the title and the question it is a basic markdown parser. I also give the inputs I will feed.

What is the valid order of convertion in case of nested similar marks? *foo *bar* foo* would be converted to foo bar foo and not to foo bar foo ?

@Dead the first one.

R E T I N A.

What about escapes? \1. should produce 1. in normal markdown, but does that apply here?

@programmer5000 uhh hmm. Sure

PHP, 770 Bytes
Online Version
There are some rules to make html with this markup
the replacement of blockquote must before all others
h6,h5,h4,h3,h2,h1 is the next order
strong, em
img, a
and (li ,ul, li,ol) or (li ,ol, li,ul)

$s=[
"%>(.*)\n%Us"
,'%(\*|_)\1(.+)\1\1%Us'
,'%(\*|_)(.*)\1%Us'
,'%######(.*)\n%Us'
,'%#####(.*)\n%Us'
,'%####(.*)\n%Us'
,'%###(.*)\n%Us'
,'%##(.*)\n%Us'
,'%#(.*)\n%Us'
,'%- (.*)\n%Us'
,'%(?<!
)
%Us'
,'%
(?!
)%Us'
,'%\d+\. (.*)\n%Us'
,'%(?<!li>|ul>)
%Us'
,'%
(?!<(li|/ul)>)%Us'
,'%(\t|    )(.*)\n%Us'
,'%!\[(.*)\]\((.*)\)%Us'
,'%\[(.*)\]\((.*)\)%Us'
];
$r=[
'
\1
'
,'\2'
,'\2'
,'
\1
'
,'
\1
'
,'
\1
'
,'
\1
'
,'
\1
'
,'
\1
'
,'
\1
'
,'

'
,'

'
,'
\1
'
,'

'
,'

'
,'
\2
'
,''
,'\1'
];
echo preg_replace($s,$r,$i);

Good job! Testing right now

Lua, 641 bytes
t={"<","&lt","^.+(>)","&gt","^(#+)(.*)",function(a,b)return("<h%d>%s</h%d>"):format(#a,b,#a)end,"^>(.*)","
%1
","^[\t ]+(.*)","
%1","!%[(.-)%]%((.-)%)",'',"%[(.-)%]%((.-)%)",'%1',"%*%*","","__","","%b","%1","","","%b**","%1","%*","","%b__","%1","_",""}for l in io.lines()do u,U=l:match("^- ")or u and print("
"),u o,O=l:match("^%d%. ")or o and print("
"),o for i=1,#t,2 do l=l:gsub(t[i],t[i+1])end print((l:gsub("^- (.*)",(U and""or"
").."
%1
"):gsub("^%d%. (.*)",(O and""or"
").."
%1
")))end

Try it online!
Readable Version and Explanation
t = { -- Table used for simple replacements
    "<", "&lt",
    "^.+(>)", "&gt", -- Cannot be at the beginning of a line because of blockquotes
    "^(#+)(.*)", function(a,b)return("<h%d>%s</h%d>"):format(#a,b,#a)end, -- Combined h# replacement
    "^>(.*)", "
%1
",
    "^[\t ]+(.*)", "
%1",
    "!%[(.-)%]%((.-)%)", '',
    "%[(.-)%]%((.-)%)", '%1',
    "%*%*", "", -- Using the actual control character is shorter than using an escape code
    "__", "",
    "%b", "%1",
    "", "",
    "%b**", "%1",
    "%*", "",
    "%b__", "%1",
    "_", ""
}

for l in io.lines() do -- For every line in STDIN
    u,U=l:match("^- ") or u and print("
"),u -- Some compact logic to print the end of the lists and mark things as such
    o,O=l:match("^%d%. ") or o and print("
"),o

    for i=1,#t,2 do
        l=l:gsub(t[i],t[i+1]) -- Run through the table of replacements
    end

    print(( -- Use two parentheses so that we only print the first return value
        l:gsub("^- (.*)", (U and "" or "
") .. "
%1
") -- Rest of the list logic
        :gsub("^%d%. (.*)", (O and "" or "
") .. "
%1
")
    ))
end

I can expand upon specific things if wanted, but it's very late as-of posting this so it'll have to wait until later.

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


text:
More cowbell...!
You are providing tech support to the Bruce Dickenson as he produces a Blue Öyster Cult recording session. When he asks for more cowbell, you can give it to him.
Your task
Write a program or function that takes a string (or equivalent in your language) as input, and outputs a related string containing one more cowbell.
How many cowbells does a string contain?
The number of cowbells a string contains equals the maximum number of distinct copies of "cowbell" that can be obtained by permuting the characters of the string. For example, "bbbccceeellllllooowwwwwwwww" contains 3 cowbells, while "bbccceeellllllooowwwwwwwww" and "bbbccceeelllllooowwwwwwwww" each contain 2 cowbells, and "cowbel" contains 0 cowbells.
How should the output be related to the input?
The output should consist of the concatenation, in this order, of the input string and the shortest prefix of the input string needed to increase the number of cowbells.
For example, "bbbccceeelllllooowwwwwwwww" only needs one additional "l" to contain 3 cowbells instead of 2; the shortest prefix that contains that "l" is "bbbccceeel". Therefore, if the input is "bbbccceeelllllooowwwwwwwww", then the output should be "bbbccceeelllllooowwwwwwwwwbbbccceeel".
Technicalities

You may assume that the input contains only printable ASCII characters. If there are one or two characters that are annoying for your language's string processing (such as newlines or \), you can assume that the input doesn't contain them—just mention this restriction.
You may further assume that the alphabetic characters in the input are all lowercase, or all uppercase. If you choose not to assume one of these, count cowbells case-insensitively.
You may further assume that the input contains at least one copy of each of the characters b, c, e, l, o, and w. This is equivalent to assuming that some prefix of the string can be concatenated to it to produce a string that contains more cowbell. (Note that the input string itself need not contain a cowbell.)
If your language has a builtin that solves this problem ... then totally use it, seriously, how awesome is that.

Gold-plated diapers
Since recording studio time is expensive, your code must be as short as possible. The entry with the fewest bytes is the winner!
Test cases
(pastebin link for easier copy/pasting)
Test input #1: "christopher walken begs for more cowbell!"
Test output #1: "christopher walken begs for more cowbell!christopher wal"
Test input #2: "the quick brown fox jumps over the lazy dog"
Test output #2: "the quick brown fox jumps over the lazy dogthe quick brown fox jumps over the l"
Test input #3: "cowbell"
Test output #3: "cowbellcowbell"
Test input #4: "cowbell cowbell cowbell"
Test output #4: "cowbell cowbell cowbellcowbell"
Test input #5: "cowbell cowbell cowbel"
Test output #5: "cowbell cowbell cowbelcowbel"
Test input #6: "bcelow"
Test output #6: "bcelowbcel"
Test input #7: "abcdefghijklmnopqrstuvwxyz"
Test output #7: "abcdefghijklmnopqrstuvwxyzabcdefghijkl"
Test input #8: "cccowwwwbbeeeeelllll"
Test output #8: "cccowwwwbbeeeeelllllccco"
Test input #9: "be well, programming puzzles & code golf"
Test output #9: "be well, programming puzzles & code golfbe well, programming puzzles & c"
Test input #10: "lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. wow!"
Test output #10: "lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. wow!lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut lab"
Test input #11:
"c-c-b-c

i have a cow, i have a bell.
uh! bell-cow!
i have a cow, i have a cowbell.
uh! cowbell-cow!

bell-cow, cowbell-cow.
uh! cow-cowbell-bell-cow.
cow-cowbell-bell-cow!
"

Test output #11:
"c-c-b-c

i have a cow, i have a bell.
uh! bell-cow!
i have a cow, i have a cowbell.
uh! cowbell-cow!

bell-cow, cowbell-cow.
uh! cow-cowbell-bell-cow.
cow-cowbell-bell-cow!
c-c-b-c

i have a cow, i have a bell"

Anyone who answers in COW earns ten internet points.

I think it would be much easier for people to handle the input/output cases if you formatted them in a single code block. As it stands it takes up a lot of space and isn't very copy paste friendly.

Pastebin link added for copy/pasting. If there's a way to hide/collapse/show the test cases in this post, thus saving vertical space, I'd love to learn it.

Well normally people use test case -> result in one large preformatted code block. It's much nicer aesthetically and easier to copy paste.

Pardon my ignorance, but who is Bruce Dickenson, and how is he related to BOC? Edit: made my way through my confusion, and found this wikipedia page

Simple answer: count C,O,W,B,E,L,L and output its minimum

@MatthewRoh Apart from the fact that there are two Ls in the word, this is not what the challenge asks.

@Pavel: I guess this is impossible in COW: I can see no way to either print a character that´s not directly from input or to reset the input pointer.

am I supposed to count cowbel letters, or should I also be including uppercase COWBEL letters as well? Something I missed in the question?

@GoldenRatio you missed You may further assume that the alphabetic characters in the input are all lowercase, or all uppercase. If you choose not to assume one of these, count cowbells case-insensitively.

Pip, 50 42 38 bytes
T$<(MN{_NaM"lcowbe"}//^2M[aYa@<i])++iy

Pass the string in as a command-line argument, quoted if necessary. Try it online!
Explanation
I'm going to explain this in two parts: the cowbell function and the full program. First, here's the function that computes the amount of cowbell in a string:
MN{_NaM"lcowbe"}//^2

{...} defines a function. Many Pip operators, when applied to a function, return another function; for example, -{a+1} is the same as {-(a+1)}. So the above is equivalent to
{MN(_NaM"lcowbe")//^2}

which works as follows:
{                    }  Function, in which a is the 1st argument (the string)
    _Na                 Lambda fn: returns number of times its argument occurs in a
       M"lcowbe"        Map that function to the characters of "lcowbe"
                   ^2   A devious way to get [2]: split the scalar 2 into characters
   (            )//     Int-divide the list of character counts by [2]
                        Since the lists are not the same length, this divides the first
                          element (# of l's) by 2 and leaves the others alone
 MN                     Take the min of the resulting list

Now that we have that, here's the full program:
T$<(MN{_NaM"lcowbe"}//^2M[aYa@<i])++iy
                                        a is 1st cmdline arg, i is 0 (implicit)
T                                       Loop till condition is true:
                            a@<i        Slice leftmost i characters of a
                           Y            Yank that into y variable
                         [a     ]       List containing a and that value
                        M               To that list, map...
    MN{_NaM"lcowbe"}//^2                ... the cowbell function
                                        Result: a list containing the amount of cowbell
                                        in the original string and the amount in the slice
 $<(                             )      Fold on less-than: true if the first element is
                                        less than the second, otherwise false
                                  ++i   In the loop, increment i
                                     y  Once the loop exits, print y (the latest slice)

I entered cowbell cowbell cowbee and the output was cowbellcowbelcowbel but I might be using the IDE wrong (new to PIP)

@AlbertRenshaw I get cowbell cowbell cowbeecowbell (try it online). Are you using TIO or a local copy?

Oh nice! I was sticking it under the field "input" not under the argument add. +1

Really top class. I ported it to javascript.

C, 511 488 474 470 463 454
void f(char*a){char*s;int i=-1,c,o,w,b,e=b=w=o=c=1,l=3,n,r,z=i;for(;s=a[++i];c+=s==67,o+=s==79,w+=s==87,b+=s==66,e+=s==69,l+=s==76);r=~-l/2;n=c<o?c:o;n=w<n?w:n;n=b<n?b:n;n=e<n?e:n;n=r<n?r:n;c=c==n;o=o==n;w=w==n;b=b==n;e=e==n;if(l=r==n?l:0)if(l%2)l=2;else l=1,c=o=w=b=e=0;else l+=l%2;n=c+o+w+b+e+l;for(printf("%s",a);s=n?a[++z]:0;s==67&&c?n--,c--:0,s==79&&o?n--,o--:0,s==87&&w?n--,w--:0,s==66&&b?n--,b--:0,s==69&&e?n--,e--:0,s==76&&l?n--,l--:0,putchar(s));}

Try it online

Readable format + explanation:
void f(char*a){
//a = input

    char*s;

    int i=-1,c,o,w,b,e=b=w=o=c=1,l=3,n,r,z=i;//c,o,w,b,e all start at 1; L starts at 3

    for(;s=a[++i];c+=s==67,o+=s==79,w+=s==87,b+=s==66,e+=s==69,l+=s==76);
    //loop to obtain number of times each character C,O,W,B,E,L is found in string (using the ASCII numeric values of each letter)

    //to get an extra cowbell we need to increment C,O,W,B,E by 1 and L by 2 (two Ls in cowbell); except we don't have to because we already did that by starting them at c=1, o=1, w=1, b=1, e=1, L=3 when we declared them.

    r=~-l/2;
    //r is half of (1 less the number of times L is in string (+ init value))

    n=c<o?c:o;n=w<n?w:n;n=b<n?b:n;n=e<n?e:n;n=r<n?r:n;
    //n is the number of times that the least occouring character appears in the string, (use R instead of L since cowbell has two L's in it and we just need ~-l/2)

    c=c==n;o=o==n;w=w==n;b=b==n;e=e==n;
    //convert c,o,w,b,e to BOOL of whether or not we need 1 more of that letter to create one more cowbell (logic for L handled below since it's trickier)

    if(l=r==n?l:0)//if L-1/2 is [or is tied for] least occurring character do below logic, else set l to 0 and skip to `else`
        if(l%2)//if l is divisible by 2 then we need 2 more Ls
            l=2;
        else //otherwise we just need 1 more l and no other letters
            l=1,c=o=w=b=e=0;
    else //add 1 to L if it's divisible by 2 (meaning just 1 more L is needed in addition to possibly other C,O,W,B,E letters) (*Note: L count started at 3, so a count of 4 would be divisible by 2 and there is only 1 L in the string)
        l+=l%2;

    n=c+o+w+b+e+l;
    //n = number of specific characters we need before we reach 1 more cowbell

    for(printf("%s",a);s=n?a[++z]:0;s==67&&c?n--,c--:0,s==79&&o?n--,o--:0,s==87&&w?n--,w--:0,s==66&&b?n--,b--:0,s==69&&e?n--,e--:0,s==76&&l?n--,l--:0,putchar(s));
    //loop starts by printing the original string, then starts printing it again one character at a time until the required number of C,O,W,B,E,L letters are reached, then break (s=n?a[++z]:0) will return 0 when n is 0. Each letter subtracts from n only when it still requires letters of its type (e.g. b?n--,b--:0)

}

Some Fun Tricks Used:
•When checking characters I type 'w' for the char w which is 3 bytes, but for the characters 'c' and 'b' I can type their ASCII values 99 and 98 respectively to save a byte each time. (Edit: Thanks to @Titus I know do this with all COWBELL letters by using uppercase input only which are all 2 bytes numeric ascii values)
•r=~-l/2 is r=(l-1)/2 using bitshifts
•a[++i] I'm getting the character at index(i) and iterating the index all at the same time. I just start i at i=-1 instead of i=0 (I do the same with z and start it as z=i to save another byte)

Save 8 bytes with uppercase input: all ASCII codes below 100.

@Titus Brilliant! Thank you Titus, editing now

We currently have a question regarding your statement "The second defined int (in this case c) is always set as 1 [...]." We'd be glad to have your statement as to why you think so over there because it just seems odd to some of us.

@Albert could it be that your program just relies on c,o,w,b,e to be initialized to the same value, instead of 1? Because your hint #2 seems to be not true, not for the C I know at least. Can you clarify? SO question

@FelixDombek I wish you had just asked here first before posting on SO; the amount of downvotes flying in from that site has completely killed my post. It's simply a matter of a typo in my code, I meant to say e=b=w=o=c=1. The second defined int (c) is always set as 1 this way so I can shorten it to just e=b=w=o=c=1. Editing my code now

@FelixDombek Now that I've fixed it, it seems it's not actually any shorter that way so oh well haha

Hm, I didn't think about that. Given that your code was already looked upon, and improved, by others, I was puzzled but also willing to accept that C works the way you say in the hint, which is easy to misunderstand. But I don't think your post deserved a downvote. Thanks for the clarification.

@FelixDombek thanks for pointing it out too! It is def. undefined behavior, I just simulated it (looped) on many IDEs and it seems to always init the int as 0. I probably could leave it after all, though my logic was designed to have them all set at 1; the fact that the test cases are working with it at 0 is coincidence I think. Cheers

Why char*s? Shouldn't it be char s?

@axiac C isn't my native language so I don't know much about how variables are declared, that may very well work but it's the same bytes either way

Python 2, 125 113 112 bytes
n=lambda s:min(s.count(c)>>(c=='l')for c in "cowbel")
def f(s,i=0):
 while n(s)==n(s+s[:i]):i+=1
 return s+s[:i]

n counts the number of cowbells

-12 bytes thanks to @Rod
-1 byte thanks to @Titus

you dont need [] for the list comprehension when it's the only parameter, also you can drop enumerate :min(s.count(c)/-~(c=='l')for c in"cowbel") where -~(n=='l') is a shorter way to write 1+(n=='l')

Wouldn´t >> be shorter than /-~?

@Titus you're right

There was an attempted edit that would have removed a byte by replacing the last newline space with a single semicolon.

@Möbius Wouldn't the return be in the while-loop then?

@ovs I don't really know I am a little fuzzy on this area of python.  I just thought you might want to know that there was an attempted edit on your question.

Perl 6, 91 bytes
{my &c={.comb.Bag.&{|.<c o w b e>,.<l>div 2}.min}
first *.&c>.&c,($_ X~[\,](.comb)».join)}

Assumes lower-case input.
How it works
Inside the lambda, another lambda for counting the number of cowbells in a string is defined as such:
my &c={                                        }  # Lambda, assigned to a variable.
       .comb                                      # Split the string into characters.
            .Bag                                  # Create a Bag (maps items to counts).
                .&{                       }       # Transform it into:
                   |.<c o w b e>,                 #   The counts of those letters, and
                                 .<l>div 2        #   half the count of "l" rounded down.
                                           .min   # Take the minimum count.

The rest of the code uses this inner lambda &c to find the result, like this:
                     [\,](.comb)».join   # All prefixes of the input,
               ($_ X~                 )  # each appended to the input.
first         ,                          # Return the first one for which:
      *.&c>                              #   The cowbell count is greater than
           .&c                           #   the cowbell count of the input.

MATL, 38 37 bytes
1 byte off thanks to @DLosc's idea of using the template string lcowbe instead of cowbel
n`Gt@q:)hXK!'lcowbe'=s32BQ/kX<wy-Q]xK

Input characters are all lowercase. If the input contains newlines, the newline character needs to be entered as its ASCII code concatenated with the normal characters (see last input in the link with all test cases).
Try it online! Or verify all test cases.

JavaScript (ES6), 106 107 113 126 141
A porting to javascript of the Pip answer by @DLosc. I needed some time to fully understand it, and it's genius.
Edit -15 bytes following the hint by @Titus, directly appending chars to the input string a and avoiding early return (so no for/if)
Edit 2 enumerating the 6 value for the Min function saves other 13 bytes
Edit 3 changed c function again. I thought the verbose length and split would be too lengthy. I was wrong.
Assuming lowercase input
a=>[...a].some(z=>c(a+=z)>b,c=a=>Math.min(...[...'lcowbe'].map((c,i)=>~-a.split(c).length>>!i)),b=c(a))&&a

Less golfed
a=>{
  c=a=>{ // cowbell functions - count cowbells
    k = [... 'lcowbe'].map((c,i) =>
          (a.split(c).length - 1) // count occurrences of c in a
           / (!i + 1) // divide by 2 if first in list ('l')
    );
    return Math.min(...k);
  };
  b = c(a); // starting number of cowbells
  [...a].some(z => ( // iterate for all chars of a until true
    a += z,
    c(a) > b // exit when I have more cowbells
  ));
  return a;
}

Test

f=
a=>[...a].some(z=>c(a+=z)>b,c=a=>Math.min(...[...'lcowbe'].map((c,i)=>~-a.split(c).length>>!i)),b=c(a))&&a

;["christopher walken begs for more cowbell!"
,"the quick brown fox jumps over the lazy dog"
,"cowbell"
,"cowbell cowbell cowbell"
,"cowbell cowbell cowbel"
,"bcelow"
,"abcdefghijklmnopqrstuvwxyz"
,"cccowwwwbbeeeeelllll"
,"be well, programming puzzles & code golf"
,"lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. wow!"
,`c-c-b-c

i have a cow, i have a bell.
uh! bell-cow!
i have a cow, i have a cowbell.
uh! cowbell-cow!

bell-cow, cowbell-cow.
uh! cow-cowbell-bell-cow.
cow-cowbell-bell-cow!
`].forEach(x=>console.log(x+'\n\n'+f(x)))

I guess that k[x]++ would fail due to undefined. But I am pretty certain that for(i=0;c(a)==c(a+=a[i++]);),a works.

@Titus I'm not sure to understand. I'll give it a try

@Titus wow 15 bytes saved, thanks alot

>>!i saves 3 bytes. Why don´t you use c(a+=z)?

@Titus I use c(a+=z). Not in the less golfed version, as it is, you see, less golfed. Using >>!i saves 1 byte (in the golfed version). Thanks again

IC. Are You sure that You need b=c(a) in the golfed version? c(a)<c(a+=z) should work, saving 3 bytes: c(a) will be evaluated before a+=z.

@Titus each time you suggest me something, it seems obviously wrong at first. Then I think again about it and, duh, you're right. I wanted to keep the original number of cowbells, before repeatedly modifying the string inside the loop. But all in all, do I need it? Probably not

CJam, 37
q___S\+{+"cowbel"1$fe=)2/+:e<\}%()#)<

Try it online
If I can exclude the " and \ characters, then…
35 bytes
q___`{+"cowbel"1$fe=)2/+:e<\}%()#)<

Try it online
Explanation
The code successively appends each character of the string to the initial string (going from original to doubled), determines the number of cowbells for each string (counting the number of occurrences of each character in "cowbel" and dividing the one for 'l' by 2, then taking the minimum), finds the position of the first string where the number of cowbells increases by 1, then takes the corresponding prefix of the input and puts it after the input string.
In order to include the original string too (with no character appended), the code prepends a neutral character to the string that's being iterated. The first version prepends a space, and the 2nd version uses the string representation, i.e. the string between double quotes.
q___          read input and make 3 more copies: one for output, one for prefix,
               one for appending and one for iterating
S\+           prepend a space to the iterating string
              or
`             get the string representation
{…}%          map each character of the string
  +           append the character to the previous string
  "cowbel"    push this string
  1$          copy the appended string
  fe=         get the number of occurrences of each "cowbel" character
  )2/+        take out the last number, divide by 2 and put it back
  :e<         find the minimum
  \           swap with the appended string
(             take out the first number (cowbells in the initial string)
)#            increment and find the index of this value in the array
)             increment the index (compensating for taking out one element before)
<             get the corresponding prefix
              another copy of the input is still on the stack
              and they are both printed at the end

I'm fine with you excluding the " and \ characters!

Bash + Unix utilities, 184 bytes
f()(tr -cd cowbel<<<"$1"|sed 's/\(.\)/\1\
/g'|sort|uniq -c|awk '{print int($1/(($2=="l")?2:1))}'|sort -n|head -1)
for((m=1;`f "$1${1:0:m}"`!=$[`f "$1"`+1];m++)){ :;}
echo "$1${1:0:$m}"

Try it online!
Thanks to @AlbertRenshaw for golfing 2 bytes off.

This can be golfed further for example just removing the spaces before and after the !=

@AlbertRenshaw Thank you -- I thought I had tried that and gotten a syntax error, but you're right. The awk part may be golfable more too; I'm not very familiar with awk.

Yeah I naively tried removing other spaces and linebreaks in your code and was getting syntax errors but on that one it worked ¯_(ツ)_/¯

Octave, 80 87 97 bytes
s=input('');k=1;do;until(x=@(A)min(fix(sum('cowbel'==A')./('111112'-48))))(b=[s s(1:++k)])>x(s);b

Try It Online!

This doesn't work when we need two ls to complete the additional cowbell. For example, on input cowbell, it incorrectly returns cowbellcowbel rather than cowbellcowbell. (I hope you can fix it—I like the atypical algorithm!)

@GregMartin Thanks! I will chek it!

JavaScript (ES6), 124 114 bytes
Thanks to Neil for saving a few bytes
a=>eval("for(c=0,d=a;(A=$=>Math.min([...'cowbel'].map(_=>($.split(_).length-1)>>(_=='l'))))(a)==A(d+=a[c++]););d")

Since this is quite different from the already existing JavaScript answer, and I put quite some time into this, I decided to create an answer myself.
Usage
f=a=>eval("for(c=0,d=a;(A=$=>Math.min([...'cowbel'].map(_=>($.split(_).length-1)>>(_=='l'))))(a)==A(d+=a[c++]););d")
f("cowbell")

Output
"cowbellcowbell"

.sort()[0] is a marvellous idea. eval is evil. :D

Thanks ;-) I first used Math.min(), but that cost a lot of characters, and I figured there'd be a shorter way. And yes, eval is really nice for golfing.

If only .sort()[0] worked, it would only cost 10 bytes, but it doesn't, and .sort((a,b)=>a-b)[0] costs 20 bytes but Math.min(...) only costs 13.

PHP, 133 bytes
a PHP port of @edc65´s JavaScript port of DLosc´s Pip answer.
function f($s){for(;$c=lcowbe[$i];)$a[$c]=substr_count($s,$c)>>!$i++;return min($a);}for($s=$argv[1];f($s)==f($s.=$s[$i++]););echo$s;

takes lower case input from command line argument. Run with -nr.
breakdown
// function to count the cowbells:
function f($s)
{
    for(;$c=lcowbe[$i];)            # loop through "cowbel" characters
        $a[$c]=substr_count($s,$c)  # count occurences in $s
            >>!$i++;                # divide by 2 if character is "l" (first position)
        return min($a);             # return minimum value
}
for($s=$argv[1];    # copy input to $s, loop:
    f($s)               # 1. count cowbells in $s
    ==                  # 3. keep looping while cowbell counts are equal
    f($s.=$s[$i++])     # 2. append $i-th character of $s to $s, count cowbells
;);
echo$s;             # print $s