text:
"cat"-like program
The mission is to implement a cat-like program (copy all STDIN to STDOUT).
Rules:

You may only use standard libraries
Indentation must be either two spaces or a single tab (in languages which require indentation)
Scripts must use shebangs
The result of cat anything.txt | ./yourprogram | diff anything.txt - should be nothing and should not be an infinite loop

Go example (84 bytes)
package main
import (
  "os"
  "io"
)
func main() {
  io.Copy(os.Stdout,os.Stdin)
}

C++ example (78 bytes)
#include<iostream>
using namespace std;
int main() {
  cout << cin.rdbuf();
}

Ruby example (44 bytes)
#!/usr/bin/env ruby
$stdout << $stdin.read

Shortest code (by bytes) wins.

Two space indentation isn't valid in Python.

This indentation thing is nonsense

@edc65 Especially because it often isn't needed.

@ProgramFOX Stoning the Rosetta.

@TheRare I'm not sure where you heard that, but any indentation is perfectly valid in Python. Different levels don't even need to have the same indentation. https://docs.python.org/3/reference/lexical_analysis.html#indentation

@Plutor Guess I've ran to some weird bugs then.

Even if there were a valid winning criterion, this seems a rather boring challenge.

The indentation rule doesn't make sense, the shebang one makes even less, because shebangs can be platform-specific, especially in the case of Python.

until end of June 2914… Woaah…

Also, person with most implementation? What?

what exactly prevents me from using cat in Bash, or all the 0 character programs in other languages?

typo indeed XD 2014

@TheRare With regards to Python indentation, it must be consistent within a block. So, each level must be self consistent, but it doesn't have to care about the other levels. If you aren't consistent within a block, then it will complain.

Why are there so many downvotes?

@professorfish: Because of the rules, I assume. Rule 2 is nonsense, rule 1 only makes sense for certain languages and counting the bytes of the shebang is a very weird form of scoring. So far, pretty much all answers seem to have ignored rule 3.

@Dennis would it be legitimate to just edit it to make it clearer?

@professorfish: The rules aren't unclear, they're just very, very strange. I don't think we should actually change the rules of a contest.

to bee correct with the size in my opinion also the size of the used interpreter must be added otherwise it is useless to compare the code snippets. also it should be cleared what happens if the code must be compiled to us (e.g java, c) what counts the size of the source code or the size of the binary ?

what about this python solution? for s in' /\___/\|(  o o  )|/   *   \|\__\_/__/meow|  /   \| / ___ \| \/___\/'.split('|'):print s

@professorfish, why are there so many upvotes?

this isn't even cat-like as much as it is echo-like.

Using cat with only one argument to just print out the file is easily the most frequent use case, but people apparently forget that cat stands for "concatenate" - most solutions here don't do that.

@orion: that's because OP ignored it too: "copy all stdin to stdout". Handling arguments is harder.

Sheesh why all the downvotes?

GolfScript, 0 characters / bytes

This could technically be considered invalid since GolfScript will append a \n, but that can be fixed with :n; (3 bytes).

Haha, +1. Explanation for people who don't speak golfscript: stdin is read to the stack when the program starts and the stack is outputted when it ends.

Nice idea, but invalid. GolfScript will append a linefeed to the input.

@Dennis That could be fixed in 3 bytes: :n; (edited)

I would say then that the zero-char solution is, unfortunately, invalid, and therefore the score is a solid 3. +1 nonetheless!

sed - 0 bytes
No command needed to cat a file with sed: all lines of input are printed without modification, so
sed ''

will act like cat for standard input, and
sed '' /etc/fstab

will print content of file.

"sed n" works for me and is one byte shorter.

@GlennRanders-Pehrson Yes, thank you. I didn't count the quotes as part of the sed script (I considered an empty script, something similar to sed -f /dev/null input). If we are to count chars on the line, your proposal saves a byte indeed.

ΒrainFuck (5 bytes)
,[.,]

Explanation:
,  Read first byte of input and place on stack
[  While top byte is not 0...
 . Print top byte from stack as ASCII and remove
 , Read next byte of input and place on stack
]  ...loop

one of those few tasks where BF is shorter than most other things...

This is less than 2 bytes (each command is 3 bits... totaling 15 bits).

It is not 3 bits when stored in ASCII format, and I wrote it as ASCII.

This will fail on files with a null in them though..

@Claudiu how else would you tell when the file ends? This is BF :P

Haskell - 17 bytes
main=interact id

id is the identity function and from the documentation :

The interact function takes a function of type String->String as its argument. The entire input from the standard input device is passed to this function as its argument, and the resulting string is output on the standard output device.

x86_64 NASM Assembly for Linux - 125 / 100
r:mov ax,0
mov di,0
mov rsi,c
mov dx,1
syscall
cmp ax,0
je e
mov di,1
syscall
jg r
e:mov ax,60
syscall
SECTION .bss
c:resw 1

I couldn't get it to fit in 100 bytes, but it is assembly.  Eight bytes could be saved at the cost of changing the return status to 1 instead of 0:
r:mov ax,0
mov di,0
mov rsi,c
mov dx,1
syscall
cmp ax,0
mov di,1
jg s
mov ax,60
s:syscall
jg r
SECTION .bss
c:resw 1

Now, if you really want 100 bytes, here is one in exactly 100 bytes.  The problem is that it doesn't exit correctly, it just segfaults:
r:mov ax,0
mov di,0
mov rsi,c
mov dx,1
syscall
cmp ax,0
mov di,1
syscall
jg r
SECTION .bss
c:resw 1

The instructions say to only use standard libraries; is there extra credit for using no libraries at all?

C 43
main(c){while((c=getchar())>=0)putchar(c);}

You can use ~(c=getchar()) instead of (c=getchar())>=0 to save 2 characters.

@nyuszika7h: EOF is typically -1, but this is not guaranteed by the standard. The standard only defines about EOF in section 7.19.1:
EOF which expands to an integer constant expression, with type int and a negative value, that is returned by several functions to indicate end-of-file, that is, no more input from a stream;

main(){for(;putchar(getchar())<127;);} what's with that? (apparently putchar's return value is casted to int so EOF becomes 255)

@bebe yes it's pity. putchar get an int but truncates it to 8 bits. (It's in the spec)

@edc65 VC++ error C2065: 'c':undeclared identifier. Yes, sorry my comment about putchar was incorrect.

@bacchusbeale compile as C, not C++. 'c' is defined as the first argument of main function

Linux/Unix tools, 16 bytes
#!/bin/sh
grep $

Other tools that work when called by bash/sh are
tr . .

and (15 bytes)
sed n

EDIT: Changed title from "bash/sh" to "Linux/Unix tools" because although the tools can be called by bash or sh they aren't actually part of bash or sh.

Copies the indentation?

@TheRare yes.  It copies "all stdin to the stdout," as required.  I guess that the 2-space indentation requirement refers to indentation of the code.

Yes, yes it does.

shebangs don't count towards your score (and why are they #!/bin/sh? that isn't bash)

@professorish /bin/sh is Bash on my platform (Ubuntu 14.04)  Perhaps I should have said Ubuntu and RedHat Fedora in my answer instead of "many systems" (will edit accordingly).  In the example for ruby shown in the question, the shebang is counted among the 44 bytes.

@GlennRanders-Pehrson hmmm I have Ubuntu 14.04 and /bin/sh definitely goes to the Bourne shell... nevermind

No modern system uses a plain Bourne shell as /bin/sh. Today /bin/sh is usually the Almquist shell, bash, or ksh93. OpenBSD uses pdksh as /bin/sh. A modern /bin/sh has POSIX features like export PARAM=value and echo $((1 + 2)). The classic SVR4 Bourne shell has fewer features but should still be enough to run this answer.

tr is part of the toolbox, tr is not bash

@Emmanuel neither is grep; in fact tr is more in Bash than grep, because tr is in coreutils and grep isn't

Node.js 55
#!/usr/bin/env node
process.stdin.pipe(process.stdout);

Could shorten by assigning p=process first to avoid repetition. Just plain #!env node works unless you've got a non-standard filesystem layout or funky $PATH stuff going on. Alternatively, drop the shebang line (so the default sh is used) and do node -e '<program>' because that's the same (6) extra number of characters and stays system-general. (If you want to join the dark side, rename your node binary to n.) Aaand drop the semicolon.

Perl (1)
0+1 for the -p parameter
If really the shebang counts, invoke it like this: perl -p nul on M$ or perl -p /dev/null on *nix so no shebang is involved :P
D:\>copy con cat.pl
#!perl -p
^Z
        1 file(s) copied.

D:\>type cat.pl
#!perl -p

D:\>type cat.pl | cat.pl
#!perl -p

D:\>

Bash, 3
If you need a shebang, #!/bin/sh or #!/bin/bash is probably fine.
Had to be done. Hopelessly uncreative.
cat

Slightly more interesting:
tee

Normally, tee FILENAME sends its input both to the file and to standard output. Without an argument, it seems to behave like cat.
Bash, 2
...if you don't mind the status message at the end and the fact that the output only comes after EOF on standard input!
dd

Removing the status message costs 4 chars for a total of 6 chars:
dd 2>a

The message is sent to the file a instead of standard output.
If you dispose of the message entirely, the total length is 14 7:
dd 2>&-

Bash/SHELF, 1
For the shebang, try
#!/bin/sh
. shelf.sh

where shelf.sh is the location of your SHELF file.
SHELF is my PYG-like golfing library for Bash.
D

D just aliases to cat. Also uncreative.
And the alias for tee is...
5

2>&- is shorter than 2>/dev/null.

CJam - 1
q

No extra newline :)

AWK - ???
The complete program in awk has only 1 char:
1

Unluckily the shebang stuff lets kinda explode it's length :(
#!/usr/bin/awk -f
1

May I copy awk into the filesystem root?  >;-)
As oneliner it is shorter:
$ awk 1 </etc/hostname
darkstar

I'm not sure what counts and what not...

In my experience, code in codegolf doesn't use shebangs, it is intended to be directly executed by the  interpreter (awk in this case).

Thinking about stdout = g(f(stdin))... <input tac|tac >output fails if the last input line has no linefeed. I like <input rev|rev >output. So far for f = g. What comes into the game for f != g? tr and it's inverse? sed and backwards? Smells not really promising...

A flash of enlightenment hit me: tee ftw!!! :)

At least in OpenBSD, printf 'full\0string' | awk 1 outputs 'full\n', so it is not perfect. I wonder if gawk or mawk does better?

Ruby, 2 bytes (or 1?)
#!/usr/bin/env ruby -p

The question states that the shabang needs to be included. The 2 bytes counted is the -p part of the shebang. The otherwise empty script makes Ruby behave exactly likes cat when run with the p switch: Run it without arguments and it will take input from stdin, or with arguments and it print the contents of those files.
edit:
Ruby, 8 bytes
@core1024 had already posted a solution in Perl similar to the one above, so here is another attempt. Note that the following are not scripts, they are Ruby programs ;)
puts *$<

Ruby, 16 bytes
I think this one is cute
print while gets

16 bit .com binary for MSDOS - 31 Bytes (112 Byte NASM Source)
00 00 BA 00 00 B9 01 00 B4 3F BB 00 00 CD 21 83 F8 00 74 09 B4 40 BB 01 00 CD 21 EB EB CD 20

The nasm source code:
c:resw 1
mov dx,c
mov cx,1
r:
mov ah,63
mov bx,0
int 33
cmp ax,0
je e
mov ah,64
mov bx,1
int 33
jmp r
e:
int 32

Build with "nasm -f bin -o cat.com cat-msdos.s".
I already provided a solution for x86_64 Linux, but was unable to get it under 100 bytes. This is over 100 bytes of assembly, but the actually binary is only 31 bytes!  This must be the simplest solution here.

Python 2.x - 56 or 61 bytes
Input limited to 10^9 bytes.
#!/usr/bin/python
from os import*
write(1,read(0,10**9))

Or for infinite input (61 bytes):
#!/usr/bin/python
from sys import*
stdout.write(stdin.read())

Not much to say, is there?

This isn't cat because it adds a linefeed or whatever your system uses (cr+lf?) to the output.

@yeti You're right. I use Windows atm, so couldn't remember that. Fixing...

@yeti Better now?

You can use 1e9 instead of 10**9 to save 2 characters. Also, the shebang doesn't count towards character count.

@nyuszika7h 1e9 is float while os.read requires an int. Also, the question specifically says to include the shebang.

I see. You can use import sys;print sys.stdin.read(), (note the trailing comma) for the second example to save 11 characters.

@nyuszika7h That prints an extra space.

I should check my suggestions before posting them. >_> It actually prints a newline for me. Python is weird.

@CeesTimmerman I know. This answer uses Python 2.

@CeesTimmerman I don't see a reason to use Python 3 yet. Python 2 is faster and often better for golfing.

@CeesTimmerman Ah, sorry then.

Java 68 104
My first approach at this:
class a{public static void main(String[]a){System.out.print(a[0]);}}

EDIT: Yeah, I misunderstood the concept, here is another attempt, I couldn't get it done in less than 100 chars so I'd appreciate any suggestion:
class a{public static void main(String[]a)throws Exception{for(;;)System.out.write(System.in.read());}}

That's not how cat works. cat displays the contents of the file(s) given as command line arguments, or takes input from stdin when there are no arguments.

@daniero Yeah I wasn't right, it works now, although much longer.

This breaks the rule about looping forever, how about: class a{public static void main(String[]a)throws Exception{int r;while(0<(r=System.in.read()))System.out.write(r);}}

Batch (8)
type CON

Type writes file content to the console and CON is treated as a file containing all console input.

I like how this has a one-to-one correspondence with Bash: type to cat, con to /dev/stdin

TI-BASIC, 12
While 1:Input Str1:Disp Str1:End

Use "Str1" instead of "A".

@CᴏɴᴏʀO'Bʀɪᴇɴ Thanks for the tip, I was really bad at TI-Basic a year ago. Only problem is you can't use the STO-> arrow but you couldn't before either. It seems so silly that I used A instead of a string var :P again, thanks for the tip!

@ThomasKwa Good idea.

Common Lisp
ECL, 106
#!/usr/local/bin/ecl -shell
(ignore-errors(loop(write-byte(read-byte *standard-input*)*standard-output*)))

SBCL, 109
#!/usr/local/bin/sbcl --script
(ignore-errors(loop(write-byte(read-byte *standard-input*)*standard-output*)))

CLISP, 188 180
#!/usr/local/bin/clisp
(let((i(make-stream 0 :element-type'(mod 256)))(o(make-stream 1
:direction :output :element-type'(mod
256))))(ignore-errors(loop(write-byte(read-byte i)o))))

These are the shortest programs that I can make, yet none are under 100 bytes.
The main problem is that *standard-input* and *standard-output* are character streams, not byte streams. A simple (loop(write-char(read-char)) would copy the characters but would fail to preserve bytes that did not form valid characters. Now my Common Lisp implementations want to use UTF-8 (perhaps because my locale is UTF-8), but I want to copy binary files that my not be valid UTF-8. Therefore I must copy bytes, not characters.
In ECL and SBCL, standard input and output are bivalent for both bytes and characters. I may use read-byte and write-byte, but those functions lack default streams, so I must pass *standard-input* and *standard-output* as arguments.
CLISP insists that *standard-input* and *standard-output* transport only characters. The way around this is to call ext:make-stream on file descriptor 0 (standard input) and file descriptor 1 (standard output) to make binary streams.
All three programs loop byte by byte. This is a slow way to copy bytes. A faster way would use a vector of 16384 bytes with read-sequence and write-sequence, but the program would be longer.

zsh, 15 bytes
#!/bin/zsh
1<&1

Note that there is no newline at the end of the file.

Some Perl:
#!/usr/bin/perl
print<>;

25 bytes with shebang. This can also be much smaller with die(), and by bending the rules ever so slightly:
die<>

Executing the 4th test could only be done like this:
cat bla|perl ./perlcat 2>&1|diff bla -

<> is an abbreviation for <STDIN>. The 25 byte print example is pretty self explanatory. die() is normally used for exiting non-zero and outputting an error message, hence using the 2>&1 to bend the rules around the 4th test.
It also appears that the semicolon is not required for the last statement in Perl, so the first example could be brought down to 24 bytes.

Perl6, 14 bytes:
.say for lines

And, if it doesn't need to be deterministically printing it in the correct order (hehe), you can use the auto-threading "map-apply"
lines>>.say

><>, 7 bytes
I know a ><> solution already exists, but I figured it would be welcome.
i:0(?;o

Click here to try it

GML, 37
while(1)show_message(keyboard_string)

Groovy - 45 bytes
#!/usr/bin/env groovy
System.out << System.in

And test:
$ cat FirstJsonObj.groovy | ./Cats.groovy | diff FirstJsonObj.groovy  -
$

Rust - 74
Really generic...
use std::io;fn main(){for l in io::stdin().lines(){io::print(l.unwrap())}}

No Comment - 12
'=|@^:'&|:'&

Unimplemented, so, yeah.

Dart - 48
import"dart:io";main(){stdout.addStream(stdin);}

Tcl 57
#!/usr/bin/env expect
while {[gets stdin d]>=0} {puts $d}

MATLAB, 18 bytes
fprintf(input(''))

Cannot use disp as it appends a newline to the output.

Swift, 32
while let l=readLine(){print(l)}

Prints every line until EOF is reached
If you're really picky that this doesn't work with an empty line at the end or whatever you can use this:
while let l=readLine(stripNewline:false){print(l,terminator:"")}

Simplex v.0.7
bg
b  ~~ take string input
 g ~~ output strip

Simple enough.

I need an "output all" character now. c:

TeaScript, 1 byte
x

Input is given in the first input field.
Compile online here.

Shell script, 11 bytes (including shebang)
#!/bin/cat

XD somehow my cat was on /usr/bin/cat XD

This isn't technically a shell script, it's a cat script. The shell isn't involved for executables with a shebang, unless the shebang happens to point to the shell.

@nyuszika7h Arguably it's a shell script that's just using cat as the shell.

But this is not a cat program. This is a quine.

@user23013 Oh, so it is.

Hassium, 52 Bytes
use IO;func main(){println(File.readText(args[0]));}

Expanded:
use IO;

func main () {
    println(File.readText(args[0]));
}

grep - 2 or 7 bytes
grep ''

Tested on Linux.
The "program" of '' is two bytes but the complete command is 7 bytes.

Actually, '' as a grep program won't work (try printf "#!/bin/grep\n''" > prog; chmod +x prog; ./prog). In your example, '' is just shell quote syntax. I can't see a way to run this with grep as interpreter, so this should count as a 7-byte shell script.

'' as a program will work from the interactive shell:
"seq 100 | grep '' | md5sum" produces the same result as
"seq 100 | md5sum"  (ignore the double quotes)

Many languages (49)
print("\\    /\\\n )  ( \')\n(  /  )\n \\(__)|");

 Because :3 is more like a tame lion.

That's not what the question is asking for, although it sounds like it :)

I couldn't resist!

Ruby, 21 characters
#!/usr/bin/env ruby
while 1;puts gets;end

but it won't stop '___'

testing command: cat anything.txt | ./cat.rb

neither will cat

@fogcityben For me cat stops looping when it reads EOF. What version of cat are you working from?


text:
Program that encodes a message into its own text
Write a program that encodes given text into its own text, provided as input, without disrupting its logic. The program must also work as a decoder, restoring the original message from its text. It must retain its encoding/decoding functions after transformation.
More formally speaking, the required program P must perform the following transformations with the given message text M:
P(M,P)->P*
P*(P*)->M
Here P* is the transformed program, which also must satisfy the above rules, that is:
P*(M2,P*)->P**
P**(P**)->M2
and so on... Each subsequent encoding doesn't erase previously encoded text, so P** carries two messages - M and M2.
The easiest way for the program to distinguish between encoding/decoding modes is by the presence of the extra argument M, but the final decision is up to you, provided it is clearly stated. The program may read it's own text from the file. If the chosen language doesn't have means for this, the source text can be passed to the program in any other way.
There are trivial solutions, of course, so this is rather a popularity contest. Nevertheless, I impose restriction forbidding comments in the program text.

If I call the transformed program P* with a new text, does P** contain both texts or only the last one?

So I am given the programs code as input when encoding and decoding?

How is the program intended to distinguish between being asked to decode an encoded message, and being asked to encode a message which just happens to be itself an encoded message?

Would it make sense to only forbid comments that are essential to how the program works (that is, removing or changing any comments should change neither the functionality of the program nor the encoded message)?

@celtschk judging by the OPs notation: if your program is given two inputs, encode the first input in the second input. if the program is given only one input, extract the string most recently encoded in that input.

Should P**(P**) return P* or M2?

@TheRare: M2, obviously. I guess P**(P*) should output M, right?

@celtschk That's correct.

@Tr00rle I really want to know if my answer is fine, because I had a bit of hard time understanding your specs.

Is there supposed to be any way to recover P* from P**? If not, why require that "P** carries two messages - M and M2"? I'm sorry, but although this challenge seems interesting, the spec is just way too confusing for me.

Perl
This is a one-liner in Perl just because it's possible.
if($ARGV[0]){open(F,__FILE__);while(<F>){print;print"$ARGV[0]\n"if/^_/;}}else{print<DATA>;}
__DATA__

The messages are written after __DATA__, most recent first.

How about healthy competition and single expression?

That's a pretty large value of one you've got there.

Python
You know what? Why not make it a single expression?
P = (lambda M,P=None:(lambda t:P[:74]+repr(M)[1:-1]+"'))"if P else M[74:-3])(''))
Pc = "(lambda M,P=None:(lambda t:P[:74]+repr(M)[1:-1]+\"'))\"if P else M[74:-3])(''))"
P2c = P('Hi there, mate!', Pc)
print "Encode tests:"
print " P2 = P('Hi there, mate!', Pc) =", P2c
exec 'P2 = ' + P2c
print " P2(\"Test 2's the best.\", P2c) =", P2("Test 2's the best.", P2c)

print "Decode tests:"
print "P2(P2) =", P2(P2c)
print "P(P2)  =", P(P2c)
print "P2(P)  =", P2(Pc)
print "P(P)   =", P(Pc)

Old message; The function P takes the arguments as specified and outputs the resulting code / decoded text.
def P(data,func=None):
    text = ""
    if func:
        return func[:35]+data+'"\n'+'\n'.join(func.split('\n')[2:])
    return data[35:].split('\n')[0][:-1]

# The source code.
Pc = """def P(data,func=None):
    text = ""
    if func:
        return func[:35]+data+'"\\n'+'\\n'.join(func.split('\\n')[2:])
    return data[35:].split('\\n')[0][:-1]"""

P2c = P('Hi there, mate!', Pc)
print "Encode test:"
print "P('Hi there, mate!', P) ->"
print P2c

# This is outputted by P('Hi there, mate!', code-of-P)
def P2(data,func=None):
    text = "Hi there, mate!"
    if func:
        return func[:35]+data+'"\n'+'\n'.join(func.split('\n')[2:])
    return data[35:].split('\n')[0][:-1]

print "P2('Text 2', P2) -<"
print P2('Text 2', P2c)

print "Decode test:"
print "P2(P2) =", P2(P2c)
print "P(P2)  =", P(P2c)
print "P2(P)  =", P2(Pc)
print "P(P)   =", P(Pc)

JavaScript
var transform = function (p, m) {
    var _M_ = '';
    var source = arguments.callee.toString();
    var msgre = /(_M_ = ').*(';)/;
    var regex = new RegExp(source.replace(/[.*+?^$\[\]{}()\\|]/g, "\\$&").replace(msgre, "$1(.*)$2"));

    var a = p.toString().match(regex);

    if (!a) {
        throw "first argument must be a transform function"
    } else {
        a = a[1];
    }

    if (typeof m == "undefined") {
        return eval("[" + a.split("|")[0] + "]").map(x=>String.fromCharCode(x)).join("");
    } else {
        a = m.toString().split("").map(x => x.charCodeAt(0)) + (a.length ? "|" + a: a);
        return eval("(" + source.replace(msgre, "$1" + a + "$2") + ")");
    }
}

Not sure if I understand the problem statement correctly: my decoder will decode any program and return the latest message that is encoded in the given program.
Test code:
P1 = transform(transform, "first message");
P2 = P1(P1, "second message");

console.log(P1(P1));
console.log(P2(P2));

console.log(P2(P1));
console.log(P1(P2));

// Unspecified behavior
console.log(transform(transform))

Batch
@echo off

setLocal enableDelayedExpansion
for /f %%a in (%0) do set a=%%a

if "%~1"=="e" (
    set /a a+=1
    echo !a! %~2 >> %0
    echo message encoded as !a!
) else if "%~1"=="d" for /f "skip=12 tokens=1*" %%a in (%0) do if "%%a"=="%~2" echo %%b

goto :EOF

Note there needs to be a carriage return after 'the last line' of goto :EOF.
This takes two inputs from stdin. The first of which is what you want to do; e, or d (encode and decode). The second input depends on the first - if the first input is e, then the second input will be the message that you want to encode - if it is d, then the second input will be the number of the message you wish to decode (that will be provided after encoding a message).
H:\uprof>ed.bat e "Just a message"
message encoded as 1

H:\uprof>ed.bat d 1
Just a message

Cobra
use System.Diagnostics
class Program
    var message as int[]? = nil
    def decode(program as String)
        temp = List<of String>(program.split('\n'))
        temp.insert(4, '\t\tEnvironment.exit(0)')
        temp.add('\t\tmessage = \'\'')
        temp.add('\t\tfor i in .message, message += Convert.toString(i to char)')
        temp.add('\t\tFile.writeAllText(\'message.txt\', message)')
        program = temp.join('\n')
        File.writeAllText('decode.cobra', program)
        process = Process()
        process.startInfo.fileName = 'cmd.exe'
        process.startInfo.arguments = '/C cobra decode.cobra'
        process.start
    def encode(message as String, program as String)
        temp = List<of String>()
        for i in message.toCharArray, temp.add(Convert.toString(i to int))
        message = '@' + Convert.toString(c'[')
        for n in temp.count-1, message += temp[n] + ','
        message += temp.pop + ']'
        temp = List<of String>(program.split('\n'))
        temp.insert(26,'\t\t.message = .message ? [message]')
        program = temp.join('\n')
        File.writeAllText('encode.cobra', program)
    def main
        #call methods here
        #.encode(message, program)
        #.decode(program)

While the idea is trivial, the execution of said idea is less-so.
Encoding
Encoding a message in the program will add the line .message = .message ? x immediately after def main. This line checks if .message is nil, and if so, then it sets .message to an integer array containing the character code values of each character in the message; the nil-check and positioning avoid overwriting the new message with an older one. The new program is saved to encode.cobra
Decoding
Decoding the program will add three lines at the end of the main method which cause the program to convert the char codes in .message to a string, which is then saved to message.txt when the new program is run. The new program is then saved to decode.cobra and the compiler is invoked on it.
decode.cobra is used like a temporary file and cannot be used to encode or decode another message, use the original or encode.cobra

source: Stack Exchange

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

sort: votes


text:
Find nth root of variable without using math operators/functions
Write a program which, given two positive integers n and x, will display the n-th root of x (which is also x1/n) in decimal to an accuracy of 0.00001. The program must output the resulting number in decimal, and it must work for any two numbers n and x. The variables may be defined in the program, or they may be inputted by the user, but it must work for any two positive integers.
However:

You may not use any arithmetic operators or bitwise operators (including +, *, ^, >>, etc.)
You may not use any built-in math functions (such as pow(), sqr(), or add()).
No web requests; the program must be completely independent from all outside sources.

Although I tagged this code-golf, a program with more code that can do the job more than 1 second faster is better. A winning program will be faster than all the other programs by more than a second. Time differences of less than 1 second will be considered negligible. If two programs complete within a second of each other, then the one with less code wins.

This might be doable with string operations. For [tag:fastest-code], we need a way to measure the speed of the program. I would like to say, "My program is s times slower than a program that uses arithmetic operators." For this, it would help to have a benchmark program, in a common language like Python, that uses arithmetic operators. The program might need to loop so it is slow enough to measure.

Is n always positive? If not, what should happen when the result is an imaginary number?

@Ypnypn: x**(1/(-n)) = 1/x**(1/n); if x is negative, then we run into complex numbers.

@KyleKanos Good point; I stand corrected.

Perhaps I am wrong, but this problem does not seem to be possible to me.

@KyleKanos I can't see why it shouldn't be possible.

@KyleKanos: I think it's possible, I'm writing a solution, but I'm not 100% sure that my logic isn't flawed and it'll actually work!

Could you please clarify how you are going to score both by code length and speed? a) as kernigh said, please state how you will be objectively comparing runtimes b) is code length just the tie breaker? Because it's virtually impossible to get a tie for fastest code, unless you score by asymptotic complexity. If it's not the tie breaker, we need a formula how length and speed factor into a single score.

@KyleKanos, it might be possible in languages which allow you to run a loop n times without using arithmetic, but most C-like languages are probably ruled out.

@PeterTaylor I don't write in C, but wouldn't appending something to a string and then checking if it's length is over a threshold (breaking if so) work?

@Ourous strings in C don't have this kind of dynamic length.

@m.buettner Oh. Well I guess I learned something new.

Can I use if x.sign == -1 instead of if x < 0, or do you consider that an operator?

@Ourous that sounds like a built-in math function to me, but what's wrong with x < 0? < is neither an arithmetic nor a bitwise operator.

@m.buettner It's a huge amount faster than x < 0, but now that I think about it I probably won't use either.

@m.buettner: I made some edits to make the winning criterion more clear; hope that helps. The code golf is the tie-breaker, and two programs tie if they complete within a second of each other.

@KyleKanos: Yeah, I accidentally made it impossible (because complex numbers can't be represented using a single decimal number). I changed it to positive integers, which is what I should have done from the beginning.

I hope I have fixed everything.

@TimothySmith so you are aware that requires you to run all submissions on your own machine in order for timings to be comparable?

@m.buettner Not necessarily. We'd just need a bit of code that can assess the speed of the computer. Then we'd be able to convert the timings to the same scale.

I believe the 1 second rule is good enough. If the actual time differences are much longer or much shorter than 1 second, then the exact speed of the computer will not matter.

I've voted to close this question as unclear, as "arithmetic operators" and "builtin math functions" are unclear terms, which do not properly cover what is allowed and what isn't

JavaScript
This answer doesn't satisfy all the rules, but I'm happy that at least it works. It's valid only for integers greater than one and there's no further precision.
Note that the + and > operators are used for string concatenation/comparison and the maths is behind the curtain. I hope that the ! operator doesn't count as "arithmetic" as it operates over booleans.
function f(x,n){for(a=(c=',')+Array(x),s=r=c;a>s;r+=c)for(i='',s=r;i!=Array(n);i+=c)s=s.split(c).join(r);return r.slice(1).length}

And some tests:

> f(125,3)
5
> f(16807,5)
7
> f(4782969,7)
9

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


text:
Find the Nth pair of twin primes
Two prime numbers are defined as twin primes if they differ by two. For example, 3 and 5 are twin primes as are 29 and 31.
Write a program that finds the nth pair of twin primes (where n comes from STDIN) and prints them on STDOUT, separated by a comma and a space. This is code-golf, so the shortest code wins.
Sample input:
3

Sample output:
11, 13

Wait... so the user will input the nth pair of twin primes, and you want us to output it? So, just echo back what the user inputs? ;-)

Hmm... That wording was a bit awkward! :P

Haskell 118
main=putStrLn.(!!)[show n++", "++show(n+2)|n<-[2..],all((>0).rem n)[2..n-1],all((>0).rem(n+2))[2..n]].(+)(-1)=<<readLn

Brute-force all twin primes and prints the nth pair.

Nice one! By seperating out the filtering function and using interact instead of putStrLn you can go even further and bring this down to 105: a#b=all((>0).rem a)[2..a-b];main=interact$(!!)[show n++", "++show(n+2)|n<-[2..],n#1,(n+2)#2].(+)(-1).read

CJam, 29 26 bytes
Y4]{{:)_{mp}/&!}g}q~*", "*

Try it online.
Examples
$ for i in {1..10}; do cjam twin-primes.cjam <<< $i; echo; done
3, 5
5, 7
11, 13
17, 19
29, 31
41, 43
59, 61
71, 73
101, 103
107, 109

How it works
Y4]        " Push [ 2 4 ].                                                            ";
{          "                                                                          ";
  {        "                                                                          ";
    :)     " Increment each integer in the array.                                     ";
    _      " Duplicate the array.                                                     ";
    {mp}/  " For each integer in the array, push 1 if it's prime and 0 otherwise.     ";
    &!     " Compute the logical NOT of the bitwise AND of the two previous integers. ";
  }g       " If the result is non-zero, repeat the loop.                              ";
}q~*       " Do the above “N” times, where “N” is the integer read from STDIN.        ";
", "       " Join the array by comma and space.                                       ";

Perl, 101 87
87 characters, building over aschepler's comment
$n=pop;$r='^1$|^(11+?)\1+$';($t=1x$s)=~$r||"11t"=~$r||--$n||die"$s, ",$s+2,$/while++$s

101 characters, earlier answer
$n=pop;$r=qr/^1$|^(11+?)\1+$/;(1x$s)!~$r&&(1x($s+2))!~$r&&++$i==$n&&say($s,", ",$s+2)&&exit while++$s

Usage:
$ perl ./twin_primes.pl 10
107, 109

Explanation
$n = pop;                 # Pulls twin prime pair counter from @ARGV
$r = qr/^1$|^(11+?)\1+$/; # The money line - a regex that verifies
                          # if a string of 1's has non-prime length

while ( ++$s ) {          # Loop over integers

                          # '&&' short-circuits
    (1 x  $s    ) !~ $r   # Negated regex match evaluates to true if $s is prime
 && (1 x ($s+2) ) !~ $r   # Same for $s + 2
 &&          ++$i == $n   # Counter to control which pair to print
 && say( $s, ", ", $s+2 ) # Print the line
 && exit                  # Terminate program
}

The workings of the non-primality regex is explained in this SO question.

..what is this?

@TheRare : It utilizes a regex to check for the primeness of a number.

You just blew my mind. Have a +1.

@TheRare : I added an explanation for why this works. I'm sure there is still room for improvement :)

Pretty much what I would have done.  Have a few shaved characters: $n=pop;$r='^1$|^(11+?)\1+$';($t=1x$s)=~$r||"11$t"=~$r||--$n||exit say("$s, ",$s+2)while++$s

@aschepler : That's some really slick golfing, thanks!

C: 113
n,c,l;main(i){for(scanf("%d",&n),l=2;n;l=c==i?n-=i==l+2,i:l,i+=2)for(c=2;c<i&&i%c++;);printf("%d, %d\n",l-2,l);}

Sample run:
$ for i in $(seq 1 10); do echo $i | ./twinprimes; done
3, 5
5, 7
11, 13
17, 19
29, 31
41, 43
59, 61
71, 73
101, 103
107, 109

Thanks for help from Dennis, bebe, and Alchymist.

You can save a few bytes by using scanf instead of command line arguments. Also, o=0 is unnecessary, since o is global.

main could hold a default int variable, incrementing c and i in between assignments and statements could shorten the code, the assignment of l could be taken back to the first for loop's third block so you would not need braces and using only one character of separator in printf could definitely make it more compact.

Thanks, bebe! I noticed that I also had c<=i-1, which is just silly.

I don't see a way to shave a byte by incrementing i in the l assignment expression, since the (new) value of i is used to decrement n. Any tips?

if i remember correctly there is one place where you can increment i, but i belive its compiler dependent :(

CJam - 26
1e4,{mp},_2f-&qi(=_2+", "\

It works for primes smaller than 10000; you can replace 4 with a higher exponent for larger numbers (potentially up to 1020), but the program will get slower and will use more memory.
Try it at http://cjam.aditsu.net/
Explanation:
1e4, creates the array [0 1 2 ... 9999]
{mp}, selects only the prime numbers
_2f- copies the array and subtracts 2 from each item
& intersects the two arrays, thus finding the lower primes from each twin prime pair
qi reads the input and converts to integer
(= adjusts the index and gets the corresponding (lower) twin prime from the array
_2+ copies the prime and adds 2
", "\ puts the comma and space between the two primes

Javascript (E6) 92 96
Shorter and compliant - use spidermonkey shell to read stdin/write stdout (with comma and space). It finds the 10000th pair 1260989, 1260991 in under a minute on my PC
Could be shorter using p[n]=o=n instead of p.push(o=n), so that the p array is sparse. But that's quite slower, and I'm not going to win for code length anyway.
m=readline();for(n=3,o=p=[];m;n+=2)p.every(e=>n%e)&&(m-=n-o<3,p.push(o=n));print(o-2+', '+o)

To try in firefox console:
m=prompt();for(n=3,o=p=[];m;n+=2)p.every(e=>n%e)&&(m-=n-o<3,p.push(o=n));alert(o-2+', '+o)

Ungolfed
A function that found all first m twins (returns the largest value):
T=m=>{
  for (o=n=3, p=[2], t=[]; !t[m-1]; n+=2)
    p.every(e => n%e) && (n-o-2 ? 0 : t.push(n), p.push(o=n))
  return t
}

Example: console.log(T(50))
[5, 7, 13, 19, 31, 43, 61, 73, 103, 109, 139, 151, 181, 193, 199, 229, 241, 271, 283, 313, 349, 421, 433, 463, 523, 571, 601, 619, 643, 661, 811, 823, 829, 859, 883, 1021, 1033, 1051, 1063, 1093, 1153, 1231, 1279, 1291, 1303, 1321, 1429, 1453, 1483, 1489]
Just the last:
L=m=>{
  for (o=n=3,p=[2]; m; n+=2)
    p.every(e => n%e) && (m -= n-o==2, p.push(o=n))
  return o
}

Then, take that 2 lines and add IO
m = prompt()
for (o=n=3, p=[2]; m; n+=2)
  p.every(e => n%e) && (m -= n-o==2, p.push(o=n))
alert('o-2+', '+o)

C#, 265
using System.Linq;class P{static void Main(string[] args){var i=int.Parse(args[0]);int f=0,c=0;for(int j=1;;j+=2){var b=(Enumerable.Range(1,j).Count(x=>j%x==0)==2);if(f==0 && b){f=j;continue;}if(b){c++;if(c==i){System.Console.WriteLine(f+","+j);break;}j-=2;}f=0;}}}

+1 but you need to add one space after the comma when you print the mnumbers

you can save two more chars: .Count(x=>j%x==0)==2) --> .Count(x=>j%x<1)<3)

also, your class could be called P instead of Program and the parameter a instead of args.

Won't compile as it is - you have an extra ) after the .Count(...)<3. You can also save a bit by changing var i=int.Parse(args[0]);int f=0,c=0; to int i=int.Parse(args[0]),f=0,c=0;. You can further save some by extracting the initialiser from the loop, so c=0;for(int j=1; => c=0,j=1;for(;.

Also, a complete rewrite of the body of the for loop, plus using a fully qualified name rather than using System: using System.Linq;class P{static void Main(string[]args){int i=int.Parse(args[0]),f=0,c=0,j=1;for(;;j+=2)if(Enumerable.Range(1,j).Count(x=>j%x<1)>2)f=0;else if(f<1)f=j;else{if(++c==i){System.Console.WriteLine(f+", "+j);break;}j-=2;f=0;}}}, 238 chars.

Fixed the problems, thanks again guys, Bob, I ommited the using, however your code doesn't compile for me.

J - 49 60 55 51 bytes
I decided to go with a simple approach. Function t finds the next twin prime given a prime number as input (now this is included in the f function). Function f finds the nth twin prime. This also happens to be the first actual program I've written in J.
f=:[:(":,', ',":@+&2)(4&p:(,{~-=2:)])^:_@>:^:(]`2:)

Examples:
   f 1
3, 5
   f 2
5, 7
   f 3
11, 13
   f 4
17, 19
   f 5
29, 31
   f 100000
18409199, 18409201

Just for some eyebrowraises, have the ungolfed version.
twin =: (4&p:)(($:@[)`(,)@.(=(]+2:)))]
f    =: ((]-2:),])((0:{twin) ^: (]`(2:)))

Explanation:
f=:[:(":,', ',":@+&2)(4&p:(,{~-=2:)])^:_@>:^:(]`2:)
                     (4&p:(,{~-=2:)])^:_@>:^:(]`2:)
                                        @>:^:(]`2:)  main loop
                                           ^:(]`2:)  Repeat n times, starting with value of 2
                                        @>:          Add one to the current value and apply to the following function.
                     (4&p:(,{~-=2:)])^:_             Get the next twin prime
                                     ^:_             Recurse until there's no change
                          (,{~-=2:)                  If next prime - current value == 2, return current value, otherwise the next prime.
                      4&p:                           Get the next prime
     (":,', ',":@+&2)                                Format the output and add 2 to the second value.
   [:                                                Apply the twin prime to the formatter.

Basically, if n is 4, this creates a recursion tree like this:
 let T be the recursion inside t
 and numbers between rows the return values of according function
   (t * n) 3
-> (t * 4) 3
-> t  t  t  t  3
   17 11 5  3
-> (T  T) (T  T) T  T  3
    17 13  11 7  5  3
-> 17

This needs a bit more work to conform to the specifications: "prints them on STDOUT, separated by a comma and a space".  Of course that's irrelevant to the algorithm, but it does increase the length of the program.

@Szabolcs better?

Sure, +1.  J is pretty cool.

@Szabolcs It really is. Although it reeeeeally bends my mind. Getting easier all the time though (this was the first program I wrote by hand). Also, thanks.

Mathematica - 63 characters
Print[#-2,", ",#]&@Nest[NestWhile[NextPrime,#,#2-#!=2&,2]&,1,n]

Notes
This is in fact a rather straightforward implementation.  Shortening resulted in almost no obfuscation.
NextPrime is a builtin that finds the next prime after a number.
NestWhile[NextPrime,#,#2-#1!=2&,2]& is an anonymous function that finds the larger prime of the next twin prime pair after a number.
Nest applies this anonymous function n times.
Print[#-2,", ",#]& is an anonymous function that prints to stdout according to the specifications.  Sadly this alone takes up 18 characters of the 63 character solution.
Example

In[1]:= Do[
         Print[#-2,", ",#]&@Nest[NestWhile[NextPrime,#,#2-#!=2&,2]&,1,n],
         {n, 1, 10}
        ]
3, 5
5, 7
11, 13
17, 19
29, 31
41, 43
59, 61
71, 73
101, 103
107, 109

Update:  Two characters could be saved by reimplementing this CJam solution.  However, this algorithm limits the maximum value of n.   Just replace the Nest... part by Intersection[#,#-2][[5]]&@Prime@Range[999]

Where's your STDIN? :)

Perl, 100 95
$n=<>;$i=3;while($c<$n&&($l=$i++)){$i++until!grep{$i%$_<1}(2..$i-1);$c++if$i-$l<3}print"$l, $i"

Ungolfed:
$n = <>;          # Read from STDIN
$i = 3;           # Tiny hack because I know I don't need the number 2
while ($c<$n && ($l = $i++)) {   # $c counts the pairs, $l is the last prime
  $i++ until ! grep {$i%$_<1} (2..$i-1);   # Increase $i until it's not divisible by anything
  $c++ if $i-$l < 3   # If $i and $l are twin primes, count it
}
print "$l, $i"    # That damned comma added a whole character to my code!

Ruby 94
require'mathn'
n=gets.to_i
a=1
(a+=2;a.prime?&&(a+2).prime?&&n-=1)while n>0
$><<"#{a}, #{a+2}"

Online test: http://ideone.com/B2wxnG

T-SQL (2008+): 344
Brute force a CTE to find primes, window function to count n, followed by a join to find the twin. Works in a second for outputs < 1,000, just under a minute for outputs < 10,000.
Golfed (SQLFiddle here):
WITH x(i) AS(SELECT 99 UNION ALL SELECT i-2
FROM x WHERE i>3),z AS(SELECT RANK()OVER(ORDER BY x.i)n,x.i
FROM x x LEFT JOIN x y ON x.i%y.i=0 AND y.i NOT IN(x.i,1)
WHERE y.i IS NULL)SELECT LTRIM(a)+', '+LTRIM(b)FROM(SELECT RANK()
OVER(ORDER BY x.i)n,x.i a,y.i b FROM z x,z y WHERE x.n=y.n-1
AND x.i=y.i-2) o WHERE n=3
OPTION(MAXRECURSION 0)

Legible:
WITH x(i) AS (
   SELECT 99
    UNION ALL
   SELECT i-2
   FROM x
   WHERE i > 3
)
,z AS (
SELECT RANK()OVER(ORDER BY x.i)n,x.i
FROM x x
WHERE NOT EXISTS
  (SELECT *
   FROM x y
   WHERE x.i%y.i = 0
    AND y.i NOT IN (x.i,1)
  )
)
SELECT LTRIM(a)+', '+LTRIM(b)
FROM (
    SELECT RANK()OVER(ORDER BY x.i)n,x.i a, y.i b
    FROM z x, z y
    WHERE x.n = y.n+1
    AND x.i = y.i+2
) o
WHERE n = 3
OPTION(MAXRECURSION 0)

Vyxal ṡ, 57 bitsv2, 8.125 7.125 bytes
Þp'⇧æ;i:⇧

Try it Online!
Bitstring:
001010110100000101111000110100001000110100111000111011110

0-indexed

You do realise that if I write this for Quantum computing all I need to write is a filter for the answer the stdin is the Q.

Probably you are well into the field of Quantum computing effectively you have all possible data and it is two filters to select first all twin primes then the nᵗʰ from stdin. So from N{`.`}#Q

what are you on about

Quibits. Actually, your Vyxal ṡ implementation reminds me.

PHP 5.4, 223
Not a smaller one, But one try from php.
$n=$argv[1];function i($k){for($i=2;$i<=(int)($k/2);$i++)if($k%$i==0)return 0;return 1;}function t($t){return (i($t) && i($t+2))?1:0;}$g=1;$d=0;do{if(t($g)==1){if($d<$n){$d++;}else{print_r([$g,$g+2]);break;}}$g++;}while(1);

C 309
Keeps getting next primes and store odd and even terms then checks if the difference is two.
int main()
{
int n;
scanf("%d",&n);
int a=2,b=3,k=2,q;
int odd=1;
int p;
if(n>0)
{
while(n)
{
k++;
p=1;
q=ceil(sqrt(k));
for(int i=2;i<=q;i++)
{
if(k%i==0)
{
p=0;
break;
}
}
if(p)
{
if(odd%2==0)a=k;
else b=k;
if(abs(a-b)==2)n--;
odd++;
}
}
}
printf("%d %d\n",a,b);
return 0;
}

Please not the square root!
for (int i=2;i*i<=k;i++)

GolfScript 46
~[1 3]\{\{))}%.{:x,{)x\%!},,2=}/*@\-.}do;', '*

Online test: link
Annotated code:
~                       # parse the input as an int
[1 3]                   # add the array [1, 3] on the stack
\                       # invert the items on the stack
{                       # begin loop
  \                     # bring the array to the top of the stack
  {))}%                 # add 2 to each of the numbers in the array
  .{:x,{)x\%!},,2=}/    # check if numbers are prime (leaves a 0 or 1 for both numbers on the stack)
  *                     # multiply the two 0/1 numbers (will only get 1 if both are 1)
  @\-                   # subtract the result from the inital int
  .                     # copy the new int value on the stack to be consumed by the 'do' loop
}do                     # repeat until the initial int was taken down to 0
                        # at this point the array contains the two numbers we're looking for
;                       # get rid of the 0 from the stack
', '*                   # format the output

R, 91 chars
a=scan();n=1;p=5;while(n!=a){p=p+1;q=p-2;if(sum(!p%%2:p,!q%%2:q)<3)n=n+1};cat(q,p,sep=", ")

Nothing really fancy:
a=scan()
n=1
p=5
while(n!=a){
    p=p+1
    q=p-2
    if(sum(!p%%2:p,!q%%2:q)<3) # Check that p and q are both primes by checking
       n=n+1                   # the number of zeroes resulting from
}                              # p modulo each integers 2 to p and same for q
cat(q,p,sep=", ")

Usage:
> a=scan();n=1;p=5;while(n!=a){p=p+1;q=p-2;if(sum(!p%%2:p,!q%%2:q)<3)n=n+1};cat(q,p,sep=", ")
1: 10
2:
Read 1 item
107, 109

Japt, 23 19 bytes
-4 bytes thanks to Shaggy
@µX°j ©°Xj}f
[UU+2]

Run it online

21 bytes

19

@Shaggy Nice! Thanks

Husk, 11 bytes
!fo=2F≠Ẋeİp

Try it online!
non-competing, since it takes input from arguments rather than STDIN.
Returns a 2-element list.
Interesting version using Ψ: Try it online!

PHP (153)
$nth=readline();$i=1;$l=1;$c=0;while(1){$q=0;for($j=1;$j<=$i;$j++){$q+=$i%$j==0?1:0;}if($q==2){if($i-$l==2&&++$c==$nth){echo"$l, $i";break;}$l=$i;}++$I;}

Readable format with properly named variables:
$nth = readline();

$i = 1;
$lastFoundPrime = 1;
$countOfFoundPrimes = 0;

while (1) {
  $quotient = 0;
  for ($j = 1; $j <= $i; $j++) {
    $quotient += $i % $j == 0 ? 1 : 0;
  }
  if ($quotient == 2) {
    if ($i - $lastFoundPrime == 2 && ++$countOfFoundPrimes == $nth) {
      echo "$lastFoundPrime, $i";
      break;
    }
    $lastFoundPrime = $i;
  }
  ++$i;
}

And wrapped in a for loop:
foreach (range(1, 10) as $nth) {

  $i = 1;
  $lastFoundPrime = 1;
  $countOfFoundPrimes = 0;
  while (1) {
    $quotient = 0;
    for ($j = 1; $j <= $i; $j++) {
      $quotient += $i % $j == 0 ? 1 : 0;
    }
    if ($quotient == 2) {
      if ($i - $lastFoundPrime == 2 && ++$countOfFoundPrimes == $nth) {
        echo "$lastFoundPrime, $i";
        break;
      }
      $lastFoundPrime = $i;
    }
    ++$i;
  }

  echo "\n";
}

Output:
3, 5
5, 7
11, 13
17, 19
29, 31
41, 43
59, 61
71, 73
101, 103
107, 109

Welcome to Code Golf, and nice answer!

@RydwolfPrograms Thank you.

APL(NARS), 63 chars
P;w;p;r
w←⎕⋄p←2
→3×⍳0≥w⋄w-←2=p-⍨r←1πp⋄p←r⋄→2
⎕←∊⍕¨3⌽', ',p,p-2

7+7+28+17+4=63 test
  P
⎕:
  1
3, 5
  P
⎕:
  1000
79559, 79561
  P
⎕:
  100000
18409199, 18409201

AWK - 129
The file fsoe-pairs.awk:
{n=2;N=1
for(;;){if(n in L){p=L[n];del L[n]}else{p=n
if(n-N==2)if(!--$0){print N", "n;exit}N=n}P=p+n++
while(P in L)P+=p;L[P]=p}}

Running it:
$ awk -f fsoe-pairs.awk
1
3, 5
$ awk -f fsoe-pairs.awk
2
5, 7
$ awk -f fsoe-pairs.awk
10
107, 109

(1st line after command is input, the 2nd one is output)
This is based on an own prime generator algorithm I call "floating sieve of erastosthenes" (until I find it described elswhere) which only stores the needed part of the sieve and the already calculated primes.

JavaScript (Node.js), 162 chars
Reads from stdin, outputs to stdout, exits "early" for input <= 0.
t=process.argv[2],c=0,l=1;if(t>0){for(i=0;;i++){p=!Array(i+1).join(1).match(/^1?$|^(11+?)\1+$/);if(p){if(i-2==l){if(c>=t-1){console.log(l+", "+i);break}c++}l=i}}}

Usage (script above saved as ntp.js):
>for /l %x in (0, 1, 10) do node ntp.js %x
>node ntp.js 0
>node ntp.js 1
3, 5
>node ntp.js 2
5, 7
>node ntp.js 3
11, 13
>node ntp.js 4
17, 19
>node ntp.js 5
29, 31
>node ntp.js 6
41, 43
>node ntp.js 7
59, 61
>node ntp.js 8
71, 73
>node ntp.js 9
101, 103
>node ntp.js 10
107, 109

Python 2 (75)
c=input()
n=3
while c:n+=2;c-=all(n%i&~2for i in range(2,n-2))
print(n-2,n)

So what's going on here?
First, let's look at the expression all(n%i&~2for i in range(2,n-2)), which checks if (n-2,n) are a pair of twin primes.
The simpler expression all(n%i for i in range(2,n)) simply checks if n is prime by trying every divisor i in the range 2<=i<=n-1, and seeing if all remainders are nonzero. This all checks exactly this, since Python treats 0 as False and all other numbers as True.
Now, observe that (n-2)%i==0 exactly when n%i==2 for divisors i>2. So, we can perform the primality check on n and n-2 at the same time by checking the remainders for both 0 and 2. This could be done as all(n%i not in [0,2] for i in range(2,n-2)). We only try divisors in the range 2<=i<=n-3 for the sake of n-2, but this suffices for n as well since n-1 and n-2 can't be divisors unless n<=4. We will only try odd n starting from 5 to avoid this complication and that of the divisor i=2.
We golf the expression n%i not in [0,2] into n%i&~2, remembering that 0 is False and other numbers are True. The operator precedence (n%i)&(~2) is exactly what's needed. The bit-complement ~2 is ...11111101, so its bitwise and with a number zeroes-out the 2's binary place value. This gives 0 (i.e., False) only for 0 and 2, exactly what we want.
Phew! Now we have that the expression all(n%i&~2for i in range(2,n-2)) checks whether n is the upper number of a twin prime pair. What remains is to iterate over them until we see c of them, where c is the inputted number. We start with 5 and counting up by 2 to avoid divisor issues. We decrement c each time we encounter an n that works, stopping when c=0. Finally, we print the twin prime pair that we end with.

T-SQL(2012+),255 characters
A more compact T-SQL twin prime finder that also gets a little bit of a speed up.
with t(n)as(select 2+number from spt_values where type='p')select*from(select concat(b,', ',a),rank()over(order by a)from(select n,lag(n)over(order by n)from t where not exists(select*from t f where f.n<t.n and t.n%f.n=0))z(a,b)where a=b+2)r(s,k)where k=2

Human readable format::
    with t(n)as(
        select 2+number
        from spt_values
        where type='p'
    )
    select *
    from(
        select concat(b,', ',a),rank() over (order by a)
        from(
            select n, lag(n) over(order by n)

    from t
        where not exists(
            select 1 from t f
            where f.n<t.n and t.n%f.n=0)
    ) z(a,b)
    where a=b+2
) r(s,k)
where k=2

The basic gist is we use the built in table of numbers (master..spt_values type='p') and alias that with a CTE as something short. We add 2 to remove the worry of pulling 0 or 1 trivial errors for our set, so now we have candidates of 2,2050.
Z the inner most query gets all primes from 2 to 2050, by filtering out any number n that is divisible by a number less than n.
We then use a nifty T-SQL 2012 windowing function lag that lets us pull the previous result, so now Z's results a and b are the primes P[n] and P[n-1] respectively. The R query creates the output string, and filters out non-twin primes and also creates a sequence number for the output we call K.
Finally the last query R allows us to filter and get the Kth twin prime by changing its variable.

Mathematica -- 71 bytes
n=Input[];
i=j=0;
While[j<n,i++;If[And@@PrimeQ[x={i,i+2}],j++]];Print@x

PHP 8.3 145char
Runs up to 10,000 actually I had difficulty with readline simulating stdin not using this very often.
Programming support: Notepad
$j=readline();for($i=1;$i<10000;$i=$i+2){if((gmp_prob_prime($i))&&(gmp_prob_prime($i+2))){$x++;}if($x==$j){break;}}echo"$i, "; $i=$i+2;echo"$i";

$j=readline();
for ($i=1;$i<10000;$i=$i+2) {
if ((gmp_prob_prime($i))&&(gmp_prob_prime($i+2))) {$x++;}
if($x==$j) {break;}
}
echo"$i, ";
$i=$i+2;
echo"$i";

Output $j=[1-12]:
3, 5
5, 7
11, 13
17, 19
29, 31
41, 43
59, 61
71, 73
101, 103
107, 109
137, 139
149, 151

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


text:
Not-endless Recursion without a base case
Write a recursive function/program, to calculate either the Factorial or the Fibonacci number of a given non-negative integer, without explicitly implementing the base case(s).
Your program/function must return/output the correct value in a reasonable time.
You cannot

Use if statement anywhere in your program/function, nor switch
nor short-if-syntax (?:). Not even loops. Basically all
control-flow statements are forbidden.
Use try, catch or exceptions of any kind.
Terminate the program (anything like exit(1)).
Use external sources (file, web, etc.)
Avoid recursion and return the proper value otherwise. (Your function must be recursive).
Use any of the standard loopholes.

You can

Use polymorphism, create threads, wrap the Integer type with your own class, or use any other mechanism your language or runtime has. (I can think of a solution that uses the lazy-evaluation, for instance). The function/program can be written as more than one function, using Mutual Recursion, if it helps you.

Please provide a short explanation of what you did.
Be creative! The winning answer is the one with the most upvotes by 2014-06-23 (a week from today).
EDIT:
Some clarifications:
Using Pattern Matching in Functional Programming Languages is OK since it's considered as Polymorphism. The solution should be trivial though, so I guess it won't have the chance to win, since it is a popularity-contest. It is still a legitimate answer.
Although some may say it's flow control in disguise, using lazy evaluation, (or short circuit evaluation) is allowed as well.

Possibly a remote duplicate of this post on StackOverflow. I think a lot of answers there could be easily adapted to be valid submissions for this challenge.

The linked definition of control flow is such that any program with no control flow statements and with a recursive call must recurse infinitely. To avoid arguments, this needs a more precise definition of exactly what is permitted and what is forbidden, and it needs to cover all the language paradigms which people might want to use.

The question should clarify whether or not it's legit to use functional languages' pattern matching, since factorial functions without apparent flow control are a textbook example for those.

Thanks for the reference. If needed, this question can be protected or closed, as you see fit.
I removed the link.
I added a restriction for Functional languages.

Lazy evaluation is a hidden flow control, really. It feels like cheating.

@Jacob are you refusing clarification? Closing.

@Davor you need some kind of flow control to do this

"super-trivial-natural solution for this" - this rule is super-unclear

Alright, I will modify it to something more specific to clarify.

@Jacob: Could you clarify how pattern matching is polymorphism?  A link would be fine, I've just not seen such a treatment before.

This seems very language specific and it seems to be about how to write if any other than the standard way.  E.g. is the Condition function of Mathematica permissible?  What about short circuiting &&?  What's not clear to me here is the principle behind accepting or rejecting a solution.  You only have a list of acceptable solution, most of which apply only to certain languages.  Less usual constructs that might be specific to a language are not mentioned.

The principle is trying to have an implicitly base case, if any at all. It's not a language specific - if you have a Condition method in Mathematica it's acceptable as well as the ?? operator in C#. I just want it to be a creative kind of task. For example you can set a timeout to a thread and run it without a base case. It does not have to be cheating the rules all the time... I expect more creative answers regardless the language, that's all :)

what do you mean by not using exception? what if my program will "accidently" throw exception?

I meant what I said - using exceptions to accomplish the task is not acceptable.

Honest question, is it possible to compute the elements of series like Fibonacci and factorial, without having a starting point, "without explicitly implementing the base case(s)"?

No. But that's where the creativity kicks in. Do it implicitly like some of the answers below

@Anton, http://en.m.wikipedia.org/wiki/Parametric_polymorphism

@Jacob: I fail to see how this has anything to do with pattern-matching (nor with case expressions, which is what pattern-matching desugars to).

C - factorial
simple as that
int not_factorial(int n){return 1;}
int factorial(int n)
{
    int (*maybe_factorial[])(int) = {factorial, not_factorial};
    return n*maybe_factorial[!(n-1)](n-1);
}

the function factorial is almost like a basic recursive approach but not_factorial only returns 1.If I create an array of function pointers
(0: fac, 1: not_fac), then I can control which one should be executed at the next call:
maybe_factorial[0](n-1) calls factorial
maybe_factorial[1](n-1) calls not_factorial.
!(n-1) means if n > 1 return 0 else return 1

Can you explain a bit how this works?

Upvoted for the sheer nerve to use this method in C, of all languages ;)

Javascript
Just a quick idea to get things going, nothing too fancy:
var t = [1];

function factorial (n) {
    var h = arguments[1] ||  1;
    t.push (t[t.length-1] * h);
    return t[n] || factorial (n,h+1);
}

This should be considered a program rather than a function, because it depends on a variable that is outside the function's scope (and it only works once), but I'll try to edit it later as a proper closure.
The trick here relies on the combination of JS's lazy evaluation and the fact that undefined object properties are merely an undefined value rather than a reason to throw an error. Rather than doing a boring recursion down from n to 0, I've decided to add a "secret" second parameter (arguments[1]) as a counter from 1 to n. Each iteration multiplies the last element of the t array by the counter, to fill the array with all the factorial values, and once the array has an nth element I stop the recursion and return it.

Short circuit evaluation looks suspiciously like control flow.

@James_pic True, but the question specifically mentions it as valid.

excuse me but h = arguments[1] ||  1 means
h = arguments[1] ? arguments[1] :  1 and this applies to the second occurrence also. (i may be wrong but i always used it this way)

@bebe h = arguments[1] ||  1 does not control the flow. It's just an operator, with two pretty simple operands. By this logic, I shouldn't be able to use any operators at all, because their result depends on the operands' values, e.g. 1+1 does not give the same result as 2+2. As for the second occurrence, as I said, the question specifically mentioned it as valid.

Technically, || can control flow (try 0 || alert("OH NOES") versus 1 || alert("OH NOES"))

@James_pic in js code golfing, || substitutes if(!something) and && substitutes if(something)
it's up to OP, if he allows it (for some reason) or not though.

I'd have to agree: || is flow control.

@svidgen I have no idea why you people are wasting your time arguing against something which the question explicitly mentions as valid. Also I really hope you realize that it's literally impossible to end a recursion without some form of flow control hidden in some level of the abstraction. Someone, somewhere, somehow, will have to use a conditional jump instruction, and the only difference between hiding it behind a logical operator and hiding it behind pattern matching is to be decided by the OP. Who, you might have noticed, has explicitly decided that it's valid.

Haskell
fib 0 = 0
fib 1 = 1
fib n = fib (n - 1) + fib (n - 2)

Thanks to pattern matching, there is no need for control structures in this function.
As Tal mentionned, this is a textbook example for functional languages, one of the first shown when learning them.

Since the OP specifically allowed poymorphism, and Haskell implements polymorphism via run-time pattern matching, this seems legit.

"Recursion without a base case" - isn't fib 0 = 0 base case?

@Davor: There is no control flow statement here, so I think this entry is valid.

Yes, but there is a base case. You need to obey all the rules, not just some.

@Davor : None of the 6 "You cannot"-rules are broken here. This entry is as valid as the other ones, and all of them define a base case.

There will always be a base case @Davor. Either you need to put it explicitly, or use the one given by you for the platform. There's no way around it. Look at the Scala answer 0 #:: 1 #::, TCL proc 0 ... proc 1 ..., C++ int Int<0>::Fact(), C int not_factorial(int n){return 1;}, JS ||  1. There will always be a base case.

C++
#include <iostream>
using namespace std;

template <int K>
class Int
    {
    public :
        int Fact(void);
    };

template<>
int Int<0>::Fact()
    {
    return 1;
    }

template<int K>
int Int<K>::Fact()
    {
    Int <K-1> x;
    return K*x.Fact();
    }

int main(void)
    {
    Int<5> A;

    cout << A.Fact() << endl;
    }

It looks like you are explicitly implementing the base case though, which is proscribed in the first paragraph of the question ?

As I understand the question, explicitly implementing the base case means writing something like if (K==0) return 1;. All answers define 0! or 1! in a way. Mine could be more obfuscated, though.

You may be right - the question is not very clear.

Python
f = lambda n: int(n==0) or n*f(n-1)

We exploit the short-circuiting behavior of or. For n=0, the base-case check returns true, which is converted to the int 1, and otherwise, the or expression evaluates to the recursive expression.

Fun fact, True == 1 and False == 0 so the int is redundant.

@TheRare I know, but someone might say that True is the wrong value for the factorial of 0 even though it converts to 1 in any arithmetic expression.

Scala
Would this be the lazy solution the OP alluded to?
// Factorial
lazy val fac: Stream[Int] = 1 #:: Stream.from(1).map{i => i * fac(i - 1)}
// Fibonacci
lazy val fib: Stream[Int] = 0 #:: 1 #:: Stream.from(2).map{i => fib(i - 1) + fib(i - 2)}

Creates a lazily evaluated stream. The first elements are hard-coded, but subsequent elements are defined recursively, with no control flow. As a side effect, values are memo-ised.

Tcl
Well, if we can't use if or switch or for or while to test then it looks like we'll have to implement our own if.
I personally feel re-implementing if is a bit more impressive than polymorphism because polymorphism (or function overloading) is still using built in language feature. What I'm doing is implementing a feature from scratch!
# First we write functions called 0 and 1
proc 0 {a b} {uplevel 1 $b}
proc 1 {a b} {uplevel 1 $a}

# Now we try to implement IF, we'll call it _I_F_
proc _I_F_ {statement a b} {
    uplevel 1 [list [expr $statement] $a $b]
}

# Now lets write a recursive countdown function
# using our scratchbuilt if:
proc countdown {number} {
    puts $number
    _I_F_ "$number>0" "count [expr $number-1]" "puts done"
}

# Lets see if it works:
countdown 10 ;# should count down to 0

Notes:

uplevel is like evel only it allows you to execute the code in any stack level you chose.
Tcl always expects a function name to be the first word of a statement. Therefore if you want to evaluate something like $a>$b or $a==$b you can't because you can't start a statement with a variable. That's what expr is for - it's a function that evaluates expressions.
Comparison expressions such as $a<$b, like in other languages, return true or false. In tcl true is canonically 1 and false is canonically 0. So the expr $statement returns 0 or 1.
We then construct a statement using list which, depending on the expr will start with 0 or 1 and uplevel it. This in turn executes either the function 0 or the function 1.

authors: n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳