text:
Create a Fanatic bot for Stack Exchange sites
Your challenge today is to cheat at badges!
You will build a bot that will connect to a Stack Exchange site, log in as you, visit the /questions page, visit a question, and then visit 9 other questions in the "related" sidebar (because that seems sufficient to count as "activity," and I need to standardize on something).
This bot must go through this process once every day, without any input or actions from the user. It should be able to be left running, and the user should be able to never touch the computer, and the consecutive days count will still be incremented. After "visiting" the site, it must print "visited".
You will assume that the user is using the Stack Exchange-provided OpenID.
The input of the program will be the site URL, SE OpenID email, and SE OpenID password. For example:
https://stackoverflow.com/ doorknob@doorknob.doorknob password

You can input these however you would like.
Your program must work for a minimum of:

https://stackoverflow.com/
https://meta.stackoverflow.com/
https://superuser.com/
https://codegolf.stackexchange.com/

(Just to make sure it is universal.)
This is code-golf, so the shortest code in bytes will win!

The minimum I needed to do for activity was visit my user page. No need to read any questions. (But don't change the rules on account of this.)

Thank goodness the challenge wasn't to create a bot that randomly downvotes 40 questions/answers each day.

Given the scope of stack exchange, it was only a matter of time until there was a question on exploiting it.

Ruby, 456 characters
require'mechanize'
s,*e=gets.split
a,o=Mechanize.new,'http://openid.stackexchange.com/'
a.agent.http.verify_mode=OpenSSL::SSL::VERIFY_NONE
l=a.get(o+'account/login').forms[0]
l.email,l.password=e
a.submit l,l.buttons[0]
g=a.get(s+'/users/login').forms.find{|f|f.action=='/users/authenticate'}
g.openid_identifier=o
a.submit g,g.buttons[-1]
loop{p=a.get s+'/questions'
10.times{p=p.links.find{|i|i.href=~/^\/questions\/\d/}.click}
puts'visited'
sleep 86400}

Ungolfed version:
require 'mechanize'

site, email, password = gets.split

agent = Mechanize.new
agent.agent.http.verify_mode = OpenSSL::SSL::VERIFY_NONE

login_form = agent.get('http://openid.stackexchange.com/account/login').forms.first
login_form.email = email
login_form.password = password
agent.submit login_form, login_form.buttons.first
puts 'logged in with SE openid'

site_login_form = agent.get(site + '/users/login').forms.find {|form| form.action == '/users/authenticate' }
site_login_form.openid_identifier = 'http://openid.stackexchange.com/'
agent.submit site_login_form, site_login_form.buttons.last
puts 'logged in to site'

loop {
    page = agent.get(site + '/questions')
    10.times do page = page.links.find{|link| link.href =~ /^\/questions\/\d/ }.click; end
    puts 'visited'
    sleep 60 * 60 * 24
}

Did you exceed the maximum storage on your Github account and start using the Q&A StackExchange format as overflow storage for your specs and source code?  ;-)

@JonathanVanMatre, wait, there's a size limit on GitHub repositories?

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


text:
Generate white noise
The challenge is: generate an audio file made of white noise.
Requirements and instructions:

Your program must generate an audio file containing only white noise, meaning its intensity is the same for all (reasonable) frequencies and nonzero [see an example plot];
One must be able to play the audio file on the latest version of VLC [at the time of writing your answer];
The program doesn't need cryptographically-strong randomness, rand functions or reading from /dev/rand is okay;
The program must be able to generate at least 1 hour of audio, at least in theory (meaning system limitations like maximum filesize don't apply);
Your score is the number of bytes in your source code, plus all bonuses that apply;
Using any third-party, external library is okay;
The program must work without access to the Internet.

Bonuses are:

-15%: Allow to specify the format of the audio file (at least two choices; the number of possible choices doesn't change the score);
-10%: Allow to specify the duration of the audio file;
-5%: Allow to specify the bitrate of the audio file.

The settings can be stored in variables, files, or given as command line parameters, your choice. Percentages are calculated from the original number of bytes, before any bonus is applied.

The problem spec seems to be describing a code colfing challenge, but the tags say otherwise.

Whoops! I'll fix that.

Perhaps the challenge should be revised to only allow "existing third party libraries" instead of "any library".

Are you going to be a stickler on the noise being white? If you really want to verify: its autocorrelogram should have a clear spike around zero, and almost nothing at any other delay. If you aren't going to be a stickler, I say that it is pointless to specify that it be white noise. Just say noise.

What about WebAudioAPI? I coded js program, that plays white noise

MATLAB, 25
wavwrite(rand(8e3,1),'a')

writes a new WAV file to disk called a. It has a sample rate of 8 kHz and a 16 bits per sample in signed integer format. The source data is uniformly distributed on the interval [0,1], which is mapped to the interval [0,32767] after the conversion to integer format.
MATLAB, 28 - 4 (10% + 5%) = 24
I'm not sure what the OP meant about how settings could be stored in variables, but I interpreted it in a way that is favorable to this case. Assuming that:

The desired bit rate (in bits/second) is provided by the user in the variable b. The bits per sample is hard-coded at 16.
The desired duration of the file (in samples) is given in the variable d.

The result is:
wavwrite(rand(d,1),b/16,'a')

MATLAB, 16 - 4 (15% + 10%) = 12
Adding another layer of sleaze in pursuit of bonuses, I make another assumption: the desired function to use to output the file should be specified in the variable f. Then the code simplifies to:
f(rand(d,1),'a')

Allowable values for the function are:
f = @wavwrite

or
f = @auwrite

Each function will cause the above snippet to write out a file of the appropriate format (WAV or .au) at a sample rate of 8 kHz with the specified duration. I took off the bonus for specification of the bitrate here, because auwrite defaults to 8 bits per sample instead of 16 like wavwrite does. I don't see a way to harmonize the two without using more characters.

Bash, 34
dd if=/dev/sda of=file.wav count=1

If you don't want hard drive 'randomness', (a lot slower)
dd if=/dev/random of=file.wav count=9

SPIN, 28
word x=0
repeat
 word[?x]=?x

Somehow I don't think the file header can be entirely random / the same as the hard disk drive first sector

@JanDvorak - it is for me

Herr Doctor may be right, if the test harness is VLC. VLC is pretty forgiving.

@jon hm... Should have known anything goes in VLC

You've generated noise, but is it white noise?

/dev/random also exists on Macs, yay! Unfortunately iTunes can't play the resulting wav file. Not that I can complain - I opted for VLc because of its forgiveness and multitude of native codecs.

You can save five characters by executing the command while the working directory is /dev.

@Steve: The noise should be white, provided that /dev/random outputs a stream of bytes that are jointly uncorrelated with one another. In that case, the autocorrelation function for the random process corresponding to the stream of samples will be zero for all nonzero lags. In the frequency domain, this corresponds to a flat power spectral density, which is the definition of white noise. It's impossible to generate perfectly white noise with pseudorandom number generators, as there is still some amount of correlation between samples, but it's good enough for engineering work.

You can save three characters by choosing a one-letter-long filename.

Bash + ALSA, score:44 (52 chars - (10% + 5%) bonuses)
Longer than the other bash answer, but accepts duration and bitrate.  Also adds a reasonably correct header to the file, so should be reasonably portable:
arecord -r$2|head -c44;head -c$[$2*$1] /dev/urandom

Save as a script, chmod +x it and run:
$ ./wav.sh 1 44100 > c.wav
Recording WAVE 'stdin' : Unsigned 8 bit, Rate 44100 Hz, Mono
$

Note, .wav output is to stdout, so it must be redirected to a file.

You could save about 1,20 characters by reading /dev/random instead of /dev/urandom, since speed is not a requirement.

output is to stdin?

Mathematica 52 - 5 = 47
g exports a white noise .wav file of s seconds and 8000 bps.
g@s_:=Export["p.wav",RandomReal@{-1,1}~Play~{t,0,s}]

Example: a 6 second white noise file is exported.
g[6]

p.wav

Supercollider, 89 - 10% = 80.1 bytes
Sadly, despite being deliberately made for generation of sound/audio, this language is not going to win here. But it's the first appearance of Supercollider on Code Golf, so that's cool!
This submission loses primarily because setting up recording and making it happen is a verbose process owing to the client/server design of this language. Still, it's a cool language with a lot of power in very little code when you ask it to do things more complex than mere white noise.
File duration is set by changing the wait() value. I could put it in a variable, but there's really no point to that as Supercollider has no stdio to speak of. The interactivity is in manipulating the code live while the server is still playing. Essentially, the IDE is the I/O (unless you build a UI for your creation).
Here's the golfed version:
{WhiteNoise.ar(1)}.play;s.prepareForRecord;Routine.run{s.record;wait(99);s.stopRecording}

Here's a golfed version with the option to record in either aiff or wav, and specify a sample format (int16, int8, and float are all options). Unfortunately, even with all the bonuses, the version above fares better. This would be 139 - 30% = 97.3 bytes.
s.recSampleFormat='int16';s.recHeaderFormat='wav';{WhiteNoise.ar(1)}.play;s.prepareForRecord;Routine.run{s.record;wait(99);s.stopRecording}

And here's an ungolfed version of the latter, so you can see what's going on.
s.recSampleFormat='int16';
s.recHeaderFormat='wav';

{WhiteNoise.ar(1)}.play;
s.prepareForRecord;

Routine.run{
    s.record;
    wait(99);
    s.stopRecording
}

one vote for use of Supercollider.  There are a lot of other puzzles it'd be GREAT for.  Check out [tag:music] and [tag:audio]

JavaScript, 167 bytes
CAUTION: Decrease volume before run. White noise is nasty
Don't generates file, maybe not what was expected.
-4 bytes hack play noise on left channel only

c=new AudioContext()
n=c.createScriptProcessor(s=512)
n.connect(c.destination)
n.onaudioprocess=e=>{a=s;while(a--){e.outputBuffer.getChannelData(0)[a]=Math.random()}}

Man, didn't read your caution .... nearly was falling from the sofa...

C 127 115 bytes
#define H htonl
main(c){for(write(1,(int[]){H(779316836),H(24),-1,H(2),H(8000),H(1)},24);;write(1,&c,1))c=rand();}

The majority of the code writes the header for a *.au file. This prints a pseudorandom sound file to standard out.
The sample rate can be adjusted by changing the 8000.
The duration can be adjusted by hitting ctrl-c whenever you want to stop :-)

source: Stack Exchange

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

authors: Евгений Новиков

sort: votes


text:
Calculate the inverse of factorial
Write the shortest code that will take any real number greater than 1 as input and will output its positive inverse factorial. In other words, it answers the question "what number factorial is equal to this number?". Use the Gamma function to extend the definition for factorial to any real number as described here.
For example:
input=6 output=3
input=10 output=3.390077654

because 3! = 6 and 3.390077654! = 10
Rules

It is forbidden to use built in factorial functions or gamma functions, or functions that rely on these functions.
The program should be able to calculate it to 5 decimal digits, with the theoretical ability to calculate it to any precision (It should contain a number that can be made arbitrary big or small to get arbitrary precision)
Any language is allowed, shortest code in characters wins.

I made a working example here. Have a look.

This could use some more test cases, in particular to cover zero and negative inputs.

I edited that the input should be greater than 1 because otherwise there could be muliple answers.

There can be multiple answers anyway unless you also add a requirement that the output must be greater than 1.

Your working example gives 3.99999 when inputted 24. So is such a solution acceptable?

yes because this can be seen as 4, to 5 decimal places correct

Question: does code have to take input & print output, or can it just define a function that works as defined? Also how are characters counted: including whitespace (matters for python indentation) or no?

It must take input and output as stated above, and whitespace will be counted as this is an important part of the code. (if not, delete the whitespace)

Is there any time constraints on this?

I will choose a winner 7 days after I posted it, I will include this in the post!

I think the last digit of input=10 output=3.390077654 should be a 1. Try it online!

ised: 72 46 characters
This is almost a perfect fit... there is a "language" out there that seems to be meant precisely for math golf: ised. Its obfuscated syntax makes for a very short code (no named variables, just integer memory slots and a lot of versatile single char operators). Defining the gamma function using an integral, I got it to 80 seemingly random characters
@4{:.1*@+{@3[.,.1,99]^x:*exp-$3}:}@6{:@{$4::@5avg${0,1}>$2}$5:}@0,0@1,99;$6:::.

Here, memory slot $4 is a factorial function, memory slot $6 bisection function and memory slot $2 is expected to be set to input (given before sourcing this code). Slots $0 and $1 are the bisection boundaries. Call example (assuming above code is in file inversefactorial.ised)
bash> ised '@2{556}' --f inversefactorial.ised
556
5.86118

Of course, you could use the builtin ! operator, in which case you get down to 45 characters
@6{:@{{@5avg${0,1}}!>$2}$5:}@0,0@1,99;$6:::.

Careful, operator precendence is weird sometimes.
Edit: remembered to inline the functions instead of saving them. Beat Mathematica with 72 characters!
@0,0@1,99;{:@{{:.1*@+{@3[.,.1,99]^x:*exp-$3}:}::@5avg${0,1}>$2}$5:}:::.

And using the ! builtin you get 41.

An year overdue update:
I just realized this was highly inefficient. Golfed-down to 60 characters:
@0#@1,99;{:@{.1*@3[.,.1,99]^@5avg${0,1}@:exp-$3>$2}$5:}:::.

If utf-8 is used (Mathematica does it too), we get to 57:
@0#@1,99;{:@{.1*@3[.,.1,99]^@5avg${0,1}·exp-$3>$2}$5:}∙.

A bit different rewrite can cut it down to 46 (or 27 if using builtin !):
{:x_S{.5@3[.,.1,99]^avgx·exp-$3*.1<$2}:}∙∓99_0

The last two characters can be removed if you are ok with having the answer printed twice.

I would be suprised if I would see someone beat this :o

@JensRenders: I just did ;)

To clarify the discussion about accuracy: it's set by .1 (integration step) and 99 (integration limit). Bisection goes to machine precision. The bisection limit @1,99 can be kept at 99 unless you want to input numbers above (99!).

@mmumboss got you again :)

JavaScript, 116 bytes
Black magic here! Gives a result in a few milliseconds.
Only elementary math functions are used: ln, pow, exponential
x=9;n=prompt(M=Math);for(i=1e4;i--;)x+=(n/M.exp(-x)/M.pow(x,x-.5)/2.5066/(1+1/12/x+1/288/x/x)-1)/M.log(x);alert(x-1)

Basically, I coded a newton solver for \$ f(y)=\Gamma(y)-n=0 \$ and \$ x=y-1 \$ (because \$ x! \$ is \$ \Gamma(x+1) \$) and approximations for gamma and digamma functions.
Gamma approximation is Stirling approximation.
Digamma approximation uses Euler Maclaurin formula. The digamma function is the derivative of gamma function divided by gamma function: \$ f'(y)=\Gamma(y) \cdot \psi(y) \$
Ungolfed :
n = parseInt(prompt());
x = 9; //first guess, whatever but not too high (<500 seems good)

//10000 iterations
for(i=0;i<10000;i++) {

  //approximation for digamma
  d=Math.log(x);

  //approximation for gamma
  g=Math.exp(-x)*Math.pow(x,x-0.5)*Math.sqrt(Math.PI*2)*(1+1/12/x+1/288/x/x);

  //uncomment if more precision is needed
  //d=Math.log(x)-1/2/x-1/12/x/x+120/x/x/x/x;
  //g=Math.exp(-x)*Math.pow(x,x-0.5)*Math.sqrt(Math.PI*2)*(1+1/12/x+1/288/x/x-139/51840/x/x/x);

  //classic newton, gamma derivative is gamma*digamma
  x-=(g-n)/(g*d);
}

alert(x-1);

Test cases :
10 => 3.390062988090518
120 => 4.99999939151027
720 => 6.00000187248195
40320 => 8.000003557030217
3628800 => 10.000003941731514

Very nice answer altough it does not meet the required precision and it only works for numbers less than 706

@JensRenders, well, I've added some iterations of the newton solver, changed the initial guess and a better approximation for gamma function. That should fits the rules now. Let me now if it's ok :)

Yes, now it's perfect, I voted it up :)

You could save 1 char: n=prompt(M=Math)

Try running your code on a large number such as $10^{10^6}$, and ensuring that you get an integer result

Mathematica - 74 54 49
The proper way will be
f[x_?NumberQ]:=NIntegrate[t^x E^-t,{t,0,∞}]
x/.FindRoot[f@x-Input[],{x,1}]

If we just drop the test ?NumberQ it would still work, but throw some nasty warnings, which would go away if we switch to symbolic integration Integrate, but this would be illegal (I suppose), because the function would automatically be converted to Gamma function. Also we can get rid of external function that way.
Anyway
x/.FindRoot[Integrate[t^x E^-t,{t,0,∞}]-Input[],{x,1}]

To heck with proper input, just function definition (can't let MatLab win)
x/.FindRoot[Integrate[t^x E^-t,{t,0,∞}]-#,{x,1}]&

If built-in factorial were allowed
N@InverseFunction[#!&]@Input[]

The above does not give an integer (which is the argument for a true factorial function).  The following does:
Floor[InverseFunction[Gamma][n]-1]

Ahh all those built-in functions! I don't think this is beatable except in a similar way.

Mathematica is so unfair for math stuff ! :D

from the name itself MATHematica

Is NumberQ pattern test required? Or parens in E^(-t)?
Is it cheating to turn NIntegrate to Integrate? Probably... :)

It's turning into a real challenge ;)

MATLAB 54 47
If I pick the right challenges MATLAB is really nice for golfing :). In my code I find the solution to the equation (u-x!)=0 in which u is the user input, and x the variable to solve. This means that u=6 will lead to x=3, etc...
@(x)fsolve(@(y)u-quad(@(x)x.^y./exp(x),0,99),1)

The accuracy can be changed by altering the upper limit of the integral, which is set at 99. Lowering this will change the accuracy of the output as follows. For example for an input of 10:
upper limit = 99; answer = 3.390077650833145;
upper limit = 20; answer = 3.390082293675363;
upper limit = 10; answer = 3.402035336604546;
upper limit = 05; answer = 3.747303578099607;

etc.

you should specify the option for accuracy as this is required in the rules! "It should contain a number that can be made arbitrary big or small to get arbitrary precision"

I don't see it in the ised and Mathematica solutions either? But I will look into it..

I see the number 99 in the ised version, and the mathematica version is beaten anyways

Given the position in the code, this is probably the upper limit for the integral. In my code this is inf. So yeah, if I change this inf into 99, my answer becomes less accurate, which means that this number influences the precision, and therefore I meet the rules. If I change it to 99 I even save a char ;)

But after changing inf to 99 does it meet the required precision?

See the edit of my answer.

Python - 199 chars
Ok, so you'll need a lot of stack space and a lot of time, but hey, it'll get there!
from random import *
from math import e
def f(x,n):
    q=randint(0,x)+random()
    z=0
    d=0.1**n
    y=d
    while y<100:
            z+=y**q*e**(-y)*d
            y+=d
    return q if round(z,n)==x else f(x,n)

Here's another approach with even more recursion.
from random import *
from math import e
def f(x,n):
    q=randint(0,x)+random()
    return q if round(h(q,0,0.1**n,0),n)==x else f(x,n)
def h(q,z,d,y):
    if y>100:return z
    else:return h(q,z+y**q*e**(-y)*d,d,y+d)

Both of these can be tested with >>>f(10,1) provided you set the recursion limit around 10000. More than one decimal place of accuracy will likely not complete with any realistic recursion limit.
Incorporating the comments and a few modifications, down to 199 chars.
from random import*
from math import*
def f(x,n):
    q=random()*x+random()
    z=y=0
    while y<100:
            z+=y**q*e**-y*0.1**n
            y+=0.1**n
    return q if round(z,n)==x else f(x,n)

This is a code-golf question, so you need to provide the shortest answer, stating the length of your solution.

A nice method but the problem is that you can not guarrantee that this will ever find the answer... Also, this is codegolf zo you might try to minimalise character use.

Python's random() uses a Mersenne Twister which I believe walks the space of Python's floats, so it should always terminate if there is an answer within the tolerance.

Do you mean that it returns every float value before repeating one? if that's the case than this code would be valid if you where able to overcome the stack overflow

It may repeat in the short term, but in the long term, a Mersenne Twister produces each output (except for 0) with roughly equal probability. Since the output space is finite, each number has a non-zero chance of appearing, and so sooner or later (much, much later) this code will hit the correct answer.

Is Python's RNG periodic?

Shave off a few chars, after def f(x,n):: q=randint(0,x)+random();z=0;y=d=0.1**n all on the next line. In your other while: z+=y**q*e**(-y)*d;y+=d (can that (-y) be -y?). Also, return[f(x,n),q][round(z,n)==x] is shorter.

And you do from math import e. from math import* is shorter, if there is no clash from it. You can remove the space after the import *: import*. And your while y>100 might work as while100<y

this doesn't actually take any input or give any output, though - it just defines a function

Comments incorporated above. Quincunx, your shortened return statement seems to cause the recursion to loop forever; I'm not familiar with that syntax. Ok, the syntax is right, but I think it's attempting to evaluate the "false" argument rather than short-circuiting.

I can not accept this answer anyways as it's clearly not capable of doing what is asked. (because of the overflow)

The code is capable, it's just that you and I may not have the time nor the computer resources to execute it to completion ;)

You are right, it does cause the recursion to loop forever. Oops. [val_1,val_2] is a list, so [val_1,val_2][boolean_condition] selectes val_2 if the condition is true, otherwise, val_1. Take a look at [tag:tips] for python.

Python 2.7 - 215 189 characters
f=lambda t:sum((x*.1)**t*2.71828**-(x*.1)*.1for x in range(999))
n=float(raw_input());x=1.;F=0;C=99
while 1:
 if abs(n-f(x))<1e-5:print x;break
 F,C,x=f(x)<n and(x,C,(x+C)/2)or(F,x,(x+F)/2)

Usage:
# echo 6 | python invfact_golf.py
2.99999904633
# echo 10 | python invfact_golf.py
3.39007514715
# echo 3628800 | python invfact_golf.py
9.99999685376

To change precision: change 1e-5 to a smaller number for greater precision, larger number for worse precision. For better precision you probably want to give a better value for e.
This just implements the factorial function as f, and then does a binary search to hone in on the most accurate value of the inverse of the input. Assumes the answer is less than or equal to 99 (it wouldn't work for an answer of 365 for sure, I get a math overflow error). Very reasonable space and time usage, always terminates.
Alternatively, replace if abs(n-f(x))<=10**-5: print x;break with print x to shave off 50 characters. It'll loop forever, giving you a more and more accurate estimate. Not sure if this would fit with the rules though.

I didn't know that site to count chars. I always use cat file | wc -c.

@rubik: oh nice, didn't think to use that. they both match =)

dg - 131 133 bytes
o,d,n=0,0.1,float$input!
for w in(-2..9)=>while(sum$map(i->d*(i*d)**(o+ 10**(-w))/(2.718281**(i*d)))(0..999))<n=>o+=10**(-w)
print o

Since dg produces CPython bytecode this should count for Python as well, but oh...
Some examples:
$ dg gam.dg
10
3.3900766499999984
$ dg gam.dg
24
3.9999989799999995
$ dg gam.dg
100
4.892517629999997
$ dg gam.dg
12637326743
13.27087070999999
$ dg gam.dg  # i'm not really sure about this one :P it's instantaneous though
28492739842739428347929842398472934929234239432948923
42.800660880000066
$ dg gam.dg  # a float example
284253.232359
8.891269689999989

EDIT: Added two bytes because I didn't remember that it should accept floats as well!

Mine gives 42.8006566063, so they match within 5 digits of precision!

That's great! I don't know where the upper bound is, but it should break somewhere. For 1e100 it gives: 69.95780520000001, for 1e150 it outputs 96.10586423000002, whereas for 1e200 it blows up. But really I don't know whether those results are reliable...

R, 92 bytes
A function, g, which takes input z and outputs the inverse factorial of that number
There is almost certainly more to be golfed out of this, so if you see something that I can improve, please let me know.
library(pryr)
g=f(z,uniroot(f(a,integrate(f(x,x^a*exp(-x)),0,Inf)$v-z),c(0,z+1),tol=1e-9)$r)

Try it online!
Ungolfed and Commented
library(pryr)                     # Add pryr to workspace
inv.factorial = f(z,              # Declare function which
  uniroot(                        # Finds the root of
    f(a, integrate(               # The integral of
      f(x, x^a*exp(-x))           # The gamma function
        ,0 ,Inf                   # From 0 to Infinity
      )$value-z                   # Minus the input value, `z`
    ), c(0, z+1),                 # On the bound of 0 to z+1
    tol = 1e-323                  # With a specified tolerance
  )$root                          # And outputs the root
)                                 # End function

Try it online!

PARI/GP, 32 bytes
If we can use solve() and \$\Gamma\$ function gamma():
f(y)=solve(x=0,100,gamma(x+1)-y)

Try it online!

Javascript (without using loops!)
To do this, I used a well-known numerical approximation of the inverse of the Stirling Factorial approximation, (and also got inspiration by this ..cough.. cough.. code of someone else...)
function f(n){
    if(n==1) return 1;
    else if(n==2) return 2;
    else if(n==6) return 3;
    else if(n==24) return 4;
    else{
        return Math.round((((Math.log(n)/Math.LN10 *  Math.log(10.) - .5 * Math.log(2.*3.141592))+(((Math.log(n)/Math.LN10 *  Math.log(10.) - .5 * Math.log(2.*3.141592))+(((Math.log(n)/Math.LN10 *  Math.log(10.) - .5 * Math.log(2.*3.141592))+(Math.log(n)/Math.LN10 *  Math.log(10.) - .5 * Math.log(2.*3.141592)))/Math.log((Math.log(n)/Math.LN10 *  Math.log(10.) - .5 * Math.log(2.*3.141592)))))/Math.log((((Math.log(n)/Math.LN10 *  Math.log(10.) - .5 * Math.log(2.*3.141592))+(Math.log(n)/Math.LN10 *  Math.log(10.) - .5 * Math.log(2.*3.141592)))/Math.log((Math.log(n)/Math.LN10 *  Math.log(10.) - .5 * Math.log(2.*3.141592)))))))/Math.log((((Math.log(n)/Math.LN10 *  Math.log(10.) - .5 * Math.log(2.*3.141592))+(((Math.log(n)/Math.LN10 *  Math.log(10.) - .5 * Math.log(2.*3.141592))+(Math.log(n)/Math.LN10 *  Math.log(10.) - .5 * Math.log(2.*3.141592)))/Math.log((Math.log(n)/Math.LN10 *  Math.log(10.) - .5 * Math.log(2.*3.141592)))))/Math.log((((Math.log(n)/Math.LN10 *  Math.log(10.) - .5 * Math.log(2.*3.141592))+(Math.log(n)/Math.LN10 *  Math.log(10.) - .5 * Math.log(2.*3.141592)))/Math.log((Math.log(n)/Math.LN10 *  Math.log(10.) - .5 * Math.log(2.*3.141592)))))))))
    }
}

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


text:
Minimal keystrokes needed to type a given text
We all know that programmers tend to be lazy. In order to maximize your free time, you decide to write a program that outputs a minimal number of keystrokes for text fed into it.

Input: Text that has to be converted into keystrokes. You may decide on how to input the text (STDIN / reading from a file provided in the arguments)
Output: The necessary actions in the following format:

They must be numbered
Hit: Pressing a key and immediately releasing it
Press: Pressing a key and not releasing it (this will never be optimal when the key is Released as the next keystroke)
Release: Releasing a Pressed key

Example:
Input:
Hello!

Output:
A naive solution would be:
1 P Shift
2 H h
3 R Shift
4 H e
5 H l
6 H l
7 H o
8 P Shift
9 H 1
10 R Shift

This would be more efficient:
1 P Shift
2 H h
3 H 1
4 R Shift
5 H Left
6 H e
7 H l
8 H l
9 H o

Environment:

The editor uses a monospaced font
Text is soft wrapped at 80 characters
Arrow up and Arrow down preserve the column, even if there are shorter lines in between
The clipboard is assumed to be empty
Num lock is assumed to be enabled
Caps lock is assumed to be disabled
Caps lock only works for the letters (i.e. no Shift Lock)

Hotkeys / Shortcuts:

Home: Jump to the beginning of the current line
End: Jump to the end of the current line
Ctrl+A: Mark everything
Ctrl+C: Copy
Ctrl+X: Cut
Ctrl+V: Paste
Shift+Cursor moving: Marking
Ctrl+F: Opens a search dialog.

Stupid text matching, no Regular Expressions
Case sensitive
Searches wrap around
Single line text input for the search
The input is prefilled with the current selection, unless there is a newline in between, the complete input is selected
Copying / Pasting works as usual
Pressing Enter performs the search, selecting the first match after the current cursor position

F3: Repeat last search
Ctrl+H: Opens a replace dialog

Stupid text matching, no Regular Expressions
Case sensitive
Replace All, with wrap around
Single line text inputs
The search input is prefilled with the current selection, unless there is a newline in between, the complete input is selected
The replace input is empty
Copying / Pasting works as usual
Tab jumps to the replace input
Pressing Enter performs the replace all. The cursor is placed after the last replacement

Rules:

Solutions must be a complete program that compiles / parses and executes without any further modification
The keyboard displayed above is the keyboard to use

It is not required to handle characters that cannot be typed with it

Every key must be released at the end
The cursor does not need to be at the end of file at the end

Scoring:
Your score is sum the amount of actions needed to type the following texts. The winner is the solution with the lowest score. Using my naive solution I get 1371 + 833 + 2006 = 4210. Beat it! I will pick a winner in two weeks.
1 My naive solution
number = 1

H = (char) -> console.log "#{number++} H #{char}"
P = (char) -> console.log "#{number++} P #{char}"
R = (char) -> console.log "#{number++} R #{char}"

strokes = (text) ->
    shiftActive = no

    for char in text
        if /^[a-z]$/.test char
            if shiftActive
                R "Shift"
                shiftActive = no

            H char
        else if /^[A-Z]$/.test char
            unless shiftActive
                P "Shift"
                shiftActive = yes

            H char.toLowerCase()
        else
            table =
                '~': '`'
                '!': 1
                '@': 2
                '#': 3
                '$': 4
                '%': 5
                '^': 6
                '&': 7
                '*': 8
                '(': 9
                ')': 0
                '_': '-'
                '+': '='
                '|': '\\'
                '<': ','
                '>': '.'
                '?': '/'
                ':': ';'
                '"': "'"
                '{': '['
                '}': ']'

            if table[char]?
                unless shiftActive
                    P "Shift"
                    shiftActive = yes

                H table[char]
            else
                H switch char
                    when " " then "Space"
                    when "\n" then "Enter"
                    when "\t" then "Tab"
                    else
                        if shiftActive
                            R "Shift"
                            shiftActive = no

                        char
    R "Shift" if shiftActive

input = ""

process.stdin.on 'data', (chunk) -> input += chunk
process.stdin.on 'end', -> strokes input

2 Easy repetition
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG
HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII
JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ
KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK
LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM

3 More complex repetition
We're no strangers to love
You know the rules and so do I
A full commitment's what I'm thinking of
You wouldn't get this from any other guy
I just wanna tell you how I'm feeling
Gotta make you understand

Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you

We've known each other for so long
Your heart's been aching but
You're too shy to say it
Inside we both know what's been going on
We know the game and we're gonna play it
And if you ask me how I'm feeling
Don't tell me you're too blind to see

Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you

Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you

(Ooh, give you up)
(Ooh, give you up)
(Ooh)
Never gonna give, never gonna give
(Give you up)
(Ooh)
Never gonna give, never gonna give
(Give you up)

We've know each other for so long
Your heart's been aching but
You're too shy to say it
Inside we both know what's been going on
We know the game and we're gonna play it

I just wanna tell you how I'm feeling
Gotta make you understand

Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you

Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you

Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you

You can use the replay program written by me to test your solutions (Note: It does not support Searching / Replacing yet, everything else should work).

I would love to see a program like this for vim.

Normally I use the mouse for part of those things.

Very interesting. I'll have a go in the morning ;3

Is Ctrl+Shift+left/right allowed for selecting entire words?

@user80551 Unfortunatly the question has gone out 5 days before, it would be unfair to others to change it. So: No, it is not.

You didn't really have to Rick Roll us, did you? :)

@FilipHaglund I did not have to, but I remembered it from another question I answered as containing repetition :)

Hmm interesting! No shift-end/shift-home?

@intx13 Unfortunatly I did not consider them when writing the question, see my answer to user80551 above.

For simplicity, can we list the key to be pressed as either its shifted or unshifted version? Or must we convert to unshifted? Meaning: "P Shift H ^ R Shift" versus "P Shift H 6 R Shift"

@intx13 Please use the unshifted one. This is not Code Golf anyway.

@TimWolla is there a "replay" program we can use to test out solutions?

@intx13 Not yet, I'll try to provide one!

@intx13 A replay program (currently w/o Search & Replace) is now available: http://jsfiddle.net/TimWolla/M4VNM/

@TimWolla I've got a bit of a problem. My solution always gives the best solution possible but it's really, really slow. At best, it'll take ~4.0676^9111 years to complete your scoring.

@Trimsty I'd say: Go ahead anyway to show off your work. I am interested in your solution (and currently you are the only one).

@Trimsty, I'm guessing you iterate all possible key-presses , replay and compare against the target text, and keep the shortest?

@intx13 Bingo. ;3

I'm kinda with @B1KMusic. To me this would be more interesting to generate solutions to vimgolf. (Which is the equivalent of what you are trying to do here just using vim commands.) This however while sounds like a fun idea reducing keystrokes is very hard (or at least I think it is) as precise movement for selection is difficult. This makes copying and pasting is a really hard task and takes almost as many keystrokes as the thing you were trying to copy. (Or at least this is how I'm reading how copy and paste works). And I don't see many other ways to reduce key strokes.

There's several bugs in the replay program. It maintains the selection as an optional pair of positions, but selections are normally just one optional position plus the cursor. This leads to bugs that the selection doesn't update on Home, End, Up, Down; also that Ctrl-A doesn't move the cursor to the end as it should. Ctrl-C, Ctrl-X do not handle 'no selection'. Cursor motion without shift should turn off selection. (It won't come as a surprise to know this means I'm writing an answer)

@bazzargh looks like I'm modifying my code before I enter s'more.

@bazzargh I think I got all those issues fixed now. Thanks!

@intx13 Shift+End / Shift+Home is now possible (due to the fixes in the selection program. Have fun!

@TimWolla it's still buggy. Home only works on the first line. You have start = 0 if start is -1, but this should just be start++. I'm not using arrow keys in my stuff, but I can see obvious bugs there too - Up won't let you stay in column 0, and Left/Right can step outside the document.

@bazzargh Those bugs are corrected as well, thanks again.

Isn't this equivalent to finding Kolmogorov complexity?

Question: If I have to type "AAAAAAAAAAAAAAAAAAAAAAAAAA", can I convert that to <press A> <release A>? It will end up generating the proper amount of As if the timing is done just right. This is optimizing keystrokes after all non?

@Claudiu It is not allowed in the question, so: No, that would be too easy (a simple regex).

May I suggest this stylistic update to your replay program?

Haskell 1309 + 457 + 1618=3384
Finally, an answer (score greatly improved once I realised there's tabs in your first test-had to edit question to see those). Compile with ghc, supply input on stdin. Example:
$ ghc keyboard.hs && echo hello|./keyboard
1 H h
2 H e
3 H l
4 H l
5 H o
6 H Enter

I tried the obvious stuff like Dijkstra but it was way too slow, even after reducing the branching to the only useful moves, which are: output the next key, or copy from the start of the line (Shift+Home, Ctrl+C, End), or paste.
So, this approach uses a fixed-length clipboard, copies when a line prefix is about to become 'useful', and keeps using that prefix as long as it would be pasteable on more lines than the prefixes of lines it reaches next. When it can't use the clipboard, it falls back on the naive solution, so it's guaranteed to beat it once the length chosen is more than the cost of a copy.
The minimum score is achieved when the prefix length is chosen to fit "Never gonna ". There are ways to improve on this, but I've had enough of reading Rick Astley.
import Data.List (isPrefixOf,isInfixOf)
import Control.Monad (foldM)
plen=12
softlines text=sl 0 [] text
  where
    sl n [] [] = []
    sl n acc [] = [(n,reverse acc)]
    sl n acc (x:xs)
      |x=='\n'||length acc==79=(n,reverse (x:acc)):(sl (n+1) [] xs)
      |otherwise=sl n (x:acc) xs
pasteable (a,b) (c,d)=(c>a && b`isInfixOf`d)
                      || (c==a && b`isInfixOf`(drop (length b) d))
findprefixes l=filter (\(a,b,c)->c/=[])
               $ map (\(a,b)->(a, b, map fst $ filter (pasteable (a,b)) l))
               $ filter (\(a,b)->length b==plen && last b/='\n')
               $ map (\(a,b)->(a, take plen b)) l
mergePrefixes [] = []
mergePrefixes (p:ps) = mergePrefixes' p ps
 where mergePrefixes' p [] = [p]
       mergePrefixes' (a,x,b) ((c,y,d):qs) =
         if length (filter (>=c) b) >= length d then
           mergePrefixes' (a,x,b) qs
         else
           (a, x, (filter (<c) b)):(mergePrefixes' (c,y,d) qs)
uc = ("~!@#$%^&*()_+<>?:{}|\""++['A'..'Z'])
lc = ("`1234567890-=,./;[]\\'"++['a'..'z'])
down c = case [[lo]|(lo,hi)<-zip lc uc,c==hi] of []->error [c];p->head p
applyPrefixToLine prefix [] s=return s
applyPrefixToLine [] line s=emit line s
applyPrefixToLine prefix line@(ch:rest) s=
 if prefix`isPrefixOf`line then
   do { s<-emitPaste s; applyPrefixToLine prefix (drop (length prefix) line) s}
 else
   do { s<-emitch s ch; applyPrefixToLine prefix rest s}
type Keystroke = (Char, [Char])
key action k (n, shift) = do
  putStrLn ((show n)++" "++[action]++" "++k)
  if k=="Shift" then return (n+1, (not shift))
  else return (n+1, shift)
emitch (m, shift) ch=
  case ch of
    '\t'->key 'H' "Tab" (m,shift)
    '\n'->key 'H' "Enter" (m,shift)
    ' '->key 'H' "Space" (m,shift)
    _->
      if shift && ch`elem`lc then
        do { key 'R' "Shift" (m, True); key 'H' [ch] (m+1, False) }
      else if not shift && ch`elem`uc then
             do { key 'P' "Shift" (m, False); key 'H' (down ch) (m+1, True) }
           else if ch`elem`lc
                then key 'H' [ch] (m, shift)
                else key 'H' (down ch) (m, shift)
emit line s = foldM emitch s line
emitPaste s = do
  s<-key 'P'"Ctrl" s
  s<-key 'H' "v" s
  key 'R' "Ctrl" s
emitCopy s = do
  s<-key 'H' "Home" s
  s<-key 'P'"Ctrl" s
  s<-key 'H' "c" s
  s<-key 'R' "Ctrl" s
  s<-key 'R' "Shift" s
  key 'H' "End" s
applyPrefix pf ((a,b):xs) p@((c,y,d):ps) s=
  if (c==a) then
    do
      s@(n, shift) <- emit y s
      s <- if shift then return s else key 'P' "Shift" s
      s <- emitCopy s
      s <- applyPrefixToLine y (drop (length y) b) s
      applyPrefix y xs ps s
  else
    do
      s<-applyPrefixToLine pf b s
      applyPrefix pf xs p s
applyPrefix "" ((a,b):xs) [] s=
  do
    s <- emit b s
    applyPrefix "" xs [] s
applyPrefix pf ((a,b):xs) [] s=
  do
    s<-applyPrefixToLine pf b s
    applyPrefix pf xs [] s
applyPrefix _ [] _ s=return s

main=do
  input <- getContents
  let lines = softlines input
  let prefixes = mergePrefixes (findprefixes lines)
  (n,shift) <- applyPrefix "" lines prefixes (1, False)
  if shift then
    key 'R' "Shift" (n, shift)
  else
    return(n,shift)

Very nice solution :) Btw: You can shave off some more characters by combining the Pastes (if possible).

That only really affects example 2 - I had a Dijkstra algorithm version that finds that, but its only usable against the first 3 lines. You can improve my solution for all the tests by trying different prefix sizes; the solution's fast enough that you can do this by brute force, only about 10 runs are required. Awkward to refactor to that in haskell though.