text:
Generate an aperiodic integer sequence
Your task is to build a piece of code that generates an aperiodic sequence of integers, either by outputting one every time it iterates, or by taking an integer n and returning the nth number in that sequence.
Now, the sequence 1, 2, 3, 4, 5, 6, ... is itself aperiodic, so I'm going to introduce a few limitations to the definition of "aperiodic" used in this problem to weed out the trivial cases:

The sequence must not be periodic modulo any integer m > 1. So a sequence like the powers of 2 would repeat 2, 4, 8, 6 all the time modulo 10, and therefore not count. (It would also repeat 0 modulo 2.)
The sequence must not become periodic after a certain number of operations - e.g. 1 2 4 8 6 2 4 8 6 ... is still considered periodic even though 1 never appears again.
The generation code must only use integers. So a piece of code that calculated the nth digit of pi (without calculating it in some integer form first) would not be acceptable.

Now, obviously every sequence performed with limited computer memory will eventually either be periodic or run out of memory, but if you can prove that your function, given infinite memory and time, will never loop back to a previous state, then it is acceptable.
The shortest code that does the above wins.

What about strings? Can we use strings or arrays of numbers?

I assume we cannot use randomness lest it would be too easy?

@JanDvorak: Yes, you can use strings, but they will factor into your code length.

And you can use randomness, but it will take too much code if you want it to be aperiodic.

Btw you can calculate the nth digit of pi using only integers.

@Howard: If you can produce to code to do that, it will be acceptable. What I meant is a code that calculates pi and then multiplies it by whatever power of 10.

I doubt anyone can beat my 2-character golfscript solution. Anyone fluent in APL?

Do rules 1 and 2 combine to prohibit sequences which become periodic modulo m? I think it matters for such a simple sequence as n!

@PeterTaylor good note - I interpreted that that they do. If not, there's a trivial one-character solution in golfscript and J

@JanDvorak Burlesque - 2 bytes: gl. Does the same thing as your GolfScript solution.

@Peter Taylor: Yes. Those rules apply together.

You might be interested in my work on BiEntropy, which evaluates the order and disorder of a finite binary sequence. The sequence 1,2,3,4,5,6... is in fact periodic (ie the first differences 0,0,0,0,0....of the sequence are perfectly periodic). http://arxiv.org/abs/1305.0954 The paper includes an evaluation of the disorder of the prime number sequence and the digits of pi and e etc.

@JanDvorak: in APL, if you want a function the best you can do is 3, I think: ⍴∘⍕ (length of string representation) or ⌊∘⍟ (floor of log-e). A (slightly cheaty) full expression could get down to 2: ⍴⍞, which reads a line from the keyboard and then tells you how long it is, so if you tell the user to only type numbers it'd work.

Golfscript, 2 characters
`,

(stringify (`) the number and count (,) the digits)
J, 3 characters
#q:

is the count (#) of the prime factors (q:) of its input.
The vector form involves more bookkeeping, but that's not our contestant:
#@q:L:0&.<

the first 40 terms are: 0 1 1 2 1 2 1 3 2 2 1 3 1 2 2 4 1 3 1 3 2 2 1 4 2 2 3 3 1 3 1 5 2 2 2 4 1 2 2 4
see more at OEIS
The sequence is 1 at every prime position, 2 at every prime multiple of a prime, 3 at every prime multiple of a product of two primes...

If you are not convinced this is aperiodic, here are plenty of other sequences:
##:

(the number of bits = floor of the base-2 logarithm)
+/#:

(count of 1-bits in the binary representation of the number). This (reduced under any modulus)
#b#:
+/b#:

(the same in base-b)
<.^.
>.^.
<.b^.
>.b^.

(floor or ceiling of the (natural) log - this time without stringification)
*./#:
+./b#:
*./b#:

(GCD or LCM of all base-b digits (except GCD of bits won't work))
1{#:!
9{#:!
({#:@!)

(second/tenth/nth highest bit of the factorial of n)
(=<.&.%:)

(Is the number equal its floor under the square root operation? Is the number equal the square of the floor of its square root? Is the number a square?)

I don't think anybody here needs convincing that the pattern of primes is aperiodic.

@breadbox the pattern of primes is aperiodic, but what about the pattern of numbers that have an odd number of prime power divisors?

For the J part of the solution, why not just use p: (the nth prime)? After all, you said yourself that the pattern of primes is aperiodic.

@Volatility the sequence of primes is periodic modulo 2 as all primes are odd. If rules 1+2 are not meant to be taken together, then a simple factorial will do (as noted by Peter Taylor). -:<:p: would likely be a valid sequence, but it's a bit longer.

Ah, missed that, sorry.

If rules 1 and 2 aren't taken together then the primes do work, because the first one is even. Even if they are, the prime indicator function works, although that seems to be 4 characters in J: 1 p:.

@PeterTaylor nice one, too

Python, 48 25 bytes
Volatility's version, using string operations:
f=lambda a:int(`2**a`[0])

Numerical version (48 bytes):
def f(a):
 m=2**a
 while m>9:
  m/=10
 return m

Sequence it returns (first 100 terms):
1 2 4 8 1 3 6 1 2 5 1 2 4 8 1 3 6 1 2 5 1 2 4 8 1 3 6 1 2 5 1 2 4 8 1 3 6 1 2 5
1 2 4 8 1 3 7 1 2 5 1 2 4 9 1 3 7 1 2 5 1 2 4 9 1 3 7 1 2 5 1 2 4 9 1 3 7 1 3 6
1 2 4 9 1 3 7 1 3 6 1 2 4 9 1 3 7 1 3 6

This returns the first digit of the ath power of 2, which is aperiodic because log10 2 is irrational, and no multiple of it besides 0 will be an integer. (So while it may look periodic for a long time, eventually there will always be something to break the period.)
I could probably golf for whitespace, but I'm not experienced with that.

Why not just f=lambda a:int(\2**a`[0])`?

@Volatility Good question. I didn't think of using string operations.

Why do people assign their lambdas to variables?

@CatsAreFluffy Unnamed lambdas weren't always allowed.

Python, 14
int.bit_length

This generates the following sequence:
>>> f=int.bit_length
>>> [f(i) for i in range(20)]
[0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5]

lambda x:\x`[0]`

Perl -p, 7 characters
$_.=/1/

Takes an integer n on the standard input and outputs the nth number in the following sequence:
11 2 3 4 5 6 7 8 9 101 111 121 131 141 151 161 171 181 191 20 211 22 23 24 25 26...

Sage, 7
Sage has the integer-part-of-the-square-root function built-in :
f=isqrt

[f(n) for n in [0..20]]
->  [0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4]

A number of OEIS sequences are also Sage built-ins named using the OEIS index, and would score a length of 16; e.g.,
f=sloane.A000120

f;[f(n) for n in [0..20]
->  1's-counting sequence: number of 1's in binary expansion of n.
    [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2]

Perl, 19 18 characters
Simplicity itself:
sub f{"@_"=~/(.)/}

Given an integer n, the function f returns the nth number in the sequence.
For those not conversant in Perl, f returns the leading decimal digit in n. As the sequence continues, you get progressively longer runs of the current number. Thus the sequence is transparently aperiodic, and avoids devolving into any of the trivial cases listed above.

+1 for simplicity. $_[0] may be replaced with "@_" for one byte.

RETURN, 9 bytes (noncompetitive)
0[' ,1+$¦{\3}§.1!]!

Try it here.
Make sure to run using "timed run," because this is an infinite stream. Also replace \3 with character U+0003.
Explanation
Basically just outputs each number reversed. I couldn't find any periodicity, but please tell me if you do.


text:
No branching please
Anyone who is moderately into low level code optimization know about the perils of branching, be it implemented as if-statements, loops or select-statements the possibility of a branch misprediction is a terrible clock-wasting thing.
Simple problems can be solved much better with simple arithmetic, so let's do that.
For the following problems all variables are 32 bit unsigned integers and the only allowed code is plain set statements involving only the following operators:
+ addition
- subtraction
* multiplication
/ integer division, rounds down, division by 0 not allowed
% modulo
& binary and
| binary or
^ binary exclusive or
>> bitshift right
<< bitshift left

Logic operators, return 1 if the expression is true and 0 if it is false.
== equal
!= not equal
< less than
<= less than or equal
> greater than
>= greater than or equal

Set operator
=

Every line must consist of a variable identifier followed by a set operator, followed by an expression.
An expression may not contain additional set operators, but may contain variable identifiers, literal numbers and parentheses.
The golfing score shall only count the number of operators.
Example:
myvar = ( ( ( foo + 5 ) * bar ) % 7 ) == 3

Has a score of 5 operators.
A solution may include as many variables as the author see fit.
Variables that have not been set have value 0.
Overflow and underflow is allowed, all negative numbers underflow, so 3 - 5 is 4294967294, even as part of a larger statement.
Task 1: Max
Two values, A and B, exist in the scope, make the RESULT variable contain the largest of those values when the program terminates.
Task 2: Median
Three values, A, B and C, exist in the scope, make the RESULT variable contain the median of those values when the program terminates.
Task 3: Square root
One value, A, exist in the scope, make the RESULT variable contain the square root of A, rounded down, when the program terminates.
It is ok to post an answer to only one or two of the questions, to some of you just finding valid solutions will be a challenge.

Where are unary operators? I don't care about - but ~ could be nice (even if I don't know what for).

Sure, 0xFFFF_FFFF_FFFF_FFFF ^ x and 0 - x. How could I have forgot?

@JanDvorak It made the shortest description, for completeness logic not ! is also pretty trivial: x == 0.

What is the behavior of division by zero?

In Mathematica (a>b) returns True or False. Boole converts False to 0 and True to 1.  Is it legal to use Boole[a-b]?

@DavidCarraher the task and the operations defined are language-independent. How you implement them is up to you.

@JanDvorak Since division by zero on an X86 CPU cause the program to halt I'll have to go with division by zero being illegal.

Task 3, 23 ops
x = (A >> 16) + A / ((A >> 13) + 511) + 15
x = (x + A/x) >> 1
x = (x + A/x) >> 1
x = (x + A/x) >> 1
RESULT = x - (x > A/x)

Using Newton's method, as the other solutions do, with a more tactfully chosen seed. The first bit A >> 16 keeps the top of the range happy, the second bit A / ((A >> 13) + 511) keeps the middle of the range happy, and the last bit 15 the bottom, and also prevents division by zero errors (15 is the largest value possible which allows 0 to converge correctly - halved three times minus correction equals zero). For the input values 225, 275625, 82137969, 2908768489 (and nearby values) the initial seed is exact. All edge cases (perfect squares, perfect squares + 1, and perfect squares - 1) on the range 0 .. 2**32-1 have been tested and are correct.
A few comments about the rules:
Overflow and underflow is allowed, all negative numbers underflow, so 3 - 5 is 4294967294, even as part of a larger statement.
That last bit turns out to be something of an innovation killer. I initially attempted a solution using a generalized form of Halley's method, but realized that it was invalid given the above restriction. The iteration (as applied to square roots) is this:
x = x * (3*A + x*x) / (A + 3*x*x)

This iteration has nice qualities that Newton's does not. It converges cubically (rather than quadratically), it converges from above or below (rather than only from above), and it is not as sensitive to a poorly chosen seed (if Newton's iteration is provided a seed which is far too low, it will greatly over-shoot the convergence point, and then need to work its way back down).
Newton's method also has the problem (at least when dealing with integers) that it will quite often reach an x such that A / x - x = 2 - in this case, it will converge to a value one larger than the proper integer root, which needs to be corrected for; Halley's method needs no such correction. But unfortunately, the value of 3*A + x*x will quite often be larger than the allowed 32-bit integer space.
There are a number of other generalized nth root algorithms, but they all share this same characteristic:
x = x + x*(v - x**n)/(v*n)
x = (x*(n+1) - x**(n+1)/v)/n
x = ((n-2)*x + (4*v*x)/(v + x**n))/n
x = x*((n+2)*v + (n-2)*x**n)/(v + x**n)/n
x = ((n-2)*x + (n*x*v)/(v + (n-1)*x**n))/(n-1)
x = ((n-2)*x + x*((n*2-1)*v + x**n)/(v + (n*2-1)*x**n))/(n-1)

x = x + 2*x*(v - x**n)/(v + x**n)/n
x = x + x*31*(v - x**n)/(10*v + 21*x**n)/n
x = x + x*561*(v - x**n)/(181*v + 380*x**n)/n
x = x + x*1153*(v - x**n)/(372*v + 781*x**n)/n

etc. Most of these display either cubic or quadratic convergence. The last four are part of a series of iterations which converges on quartic convergence. But in praxis, Newton's method will get you what you need with fewer operations, unless you need to calculate many hundreds of digits.

Pretty nice, but fails for 4294967295. As for the rules, they gotta be tight to make it interesting. You can argue what exact premises make the best challenge, but ultimately it is far more important that the rules are clear and unambiguous, than what exactly they allow.

I don't think Halley would have been worth it anyway, from a far off guess it will improve by a little less than a factor of 3, Newton does a little less than a factor of 2. Similarly from a good guess Halley will triple the accuracy, Newton will double it. So one Halley iteration is worth pretty exactly log(3)/log(2) ~= 1.585 Newton iterations.

@eBusiness I initially had 2 Halley's with a similarly chosen seed totaling 25 ops - with error when A = 0 - so this is in fact shorter. About 4294967295, that was an oversight: as 65536² ≡ 0, the correction iteration fails to correct. I'll see if I can find an alternative.

@eBusiness fixed.

Sleekest square root of the pack, nice job, and an official victory badge.

Task 3, 39 Operations
EDIT: Changed last line; see comments.
This is an implementation of the Newthon method.
Tested with all positive squares, and also with the positive squares minus one, and also one million random numbers in the range from 0 to 2^32-1.
The seemingly funny starting value is short for (1022 + A/1022) / 2, which needs the least number of iterations (I think), and also makes the RESULT for A=0 right (which would not be the case for 1024 instead of 1022).
r = (511 + A/2044)
r = (r + A/r) / 2
r = (r + A/r) / 2
r = (r + A/r) / 2
r = (r + A/r) / 2
r = (r + A/r) / 2
r = (r + A/r) / 2
r = (r + A/r) / 2
r = (r + A/r) / 2
RESULT = r - (r > A/r)

Should I keep my inferior copy of newton's method that was optimised in parallel with yours and posted a decent amount of time later? Great minds think alike and having the solution split across two two answers is bad, but that's what the current state of affairs is, as you haven't answered #2.

@JanDvorak: Thanks for asking. It's OK if you put my slightly shorter method into your answer. Also, thanks for giving credit to me :-)

Really nice try, but fails for input 4294965360 through 4294967295.

@eBusiness: What result do you get for those inputs? I get 65535 in my tests, which is OK.

I get 65536. Maybe you don't use the prescribed integer format.

@eBusiness: Ah, thanks for the hint. r*r overflows in those cases. (r > A / r) should work.

65(61) operations (5 + 13 + 47(43))
Task 1 -- Max(A,B)
RESULT = A + (B - A) * (A <= B)

This is the obvious solution. You need the assignment, you need comparison, you need to multiply the comparison with something, the multiplicand cannot be one of the variables and the product cannot be the result.
Task 2 -- Mid(A,B,C)
RESULT = A                               \
       + (B - A) * (A > B) ^ (B <= C)    \
       + (C - A) * (A > C) ^ (C <  B)

This is an improvement over my previous 15-op solution, which conditioned all three variables - this saved two subtractions, but it introduced another centrality test. The test itself is simple: an element is in the middle iff exactly one other of the two is above.
Task 3 -- sqrt(A)
X1     = 1024 + A / 2048
X2     = (X1  + A / X1 ) / 2
...
X10    = (X9 + A / X9 ) / 2
RESULT = X16 - (X16 * X16 > A)

Eleven rounds of newton approximation. The magic constant of 1024 is already beaten by WolframW (and 512 causes division by zero for a=0 before a=2**32 converges), but if we can define 0/0 as zero, ten iterations will work with the starting value of 512. I do admit that my claim of ten iterations is not entirely clean, but I still claim them in parentheses.  I'll have to investigate if nine is possible, however. WolframH's solution is nine iterations.

I think the first line of Task 3 is not right: the second constant should be 4 times the first constant (to have "pure" Newton).

@WolframH A better initial guess might explain why I'm wasting cycles. Where did you come up with 4*? This looks like two iterations rolled into one.

(1024 + A/1024)/2 == (512 + A/2048) (which is like X0 = 1024, and then starting Newton).

Nice solution to Task 1. Columbus' egg.

@DavidCarraher of course, the correct solution would be MOV RESULT, A; CMP A,B; CMOVA RESULT, B ;-)

In most languages * takes precedence over ^, a few more brackets in your task 2 solution wouldn't hurt. And that square root task just keeps on giving, your 43 operations version fails for A=0, and the 47 operations version fails for A=4294967295. I guess that is as short as task 1 and 2 will get, so good job on those.

1: 5 operators
RESULT = B ^ (A ^ B)*(A > B)

2: 13 operators
RESULT = B ^ (A ^ B)*(A > B) ^ (A ^ C)*(A > C) ^ (B ^ C)*(B > C)

3: 27 operators
g = 47|((0x00ffffff & A)>>10)|(A>>14)
r = (g + A/g)/3
r = (r + A/r)>>1
r = (r + A/r)>>1
r = (r + A/r)>>1
RESULT = r - (r*r-1>=A)

source: Stack Exchange

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

sort: votes


text:
javascript: smallest code to convert seconds to time
Given seconds like 11728, write the smallest javascript function that returns a string like 3hrs. 15min. 28sec.
signature textTime([int] t,[bool] z,[bool] m)
t is the time like 11728 and you can assume int
z is optional and true means drop zero times, so 3hrs. 0min. 28sec. becomes 3hrs. 28sec.
m is optional and true means show only up to minutes, so 3hrs. 16min. 48sec. is 3hrs. 16min.
For 1 hour, 1hrs. is fine (vs 1hr.)
Example:
textTime(11728) returns "3hrs. 0min. 28sec."
textTime(11728,true) returns "3hrs. 28sec."
textTime(11728,true,true) returns "3hrs."

Regex is fine, speed is inconsequential.
Shortest code wins.

Your function parameters don't make any sense.

What about days, weeks, months and years? Examples don't make a specification.

this is not "date time", but a measure of hours and minutes and seconds.  1 day is not exactly 24hours and 0 secs, so a lot of things are measured in hours, which is the highest level measure of "real" time

I apologize for using [brackets] to state the var type, which made it look like an array.  maybe [int] t  would have been better.

http://jsfiddle.net/CA6GM/2/ "Javascript 120"

Javascript,  194  192
function T(a,c,e){d=60;s=["sec","min","hrs"];alert(t=[a,(0|a/d)*d,(0|a/d/d)*d*d].map(function(a,b,f){p=(a-(0|f[b+1]))/Math.pow(d,b);return e&&1>b?"":c&&!p?"":p+s[b]+". "}).reverse().join(""))}

Run it e.g. with
T(7215,true,false) //2hrs. 15sec.
Could probably be golfed a bit more
Edit Notes:
Added function name for the cost of 1 character*
Renamed the function to T. I'm assigning t in the function hence i was overwriting the function itself.
Changed (a/(d*d)) -> (a/d/d)

Excellent!, it works in all cases.  I'm marking this as the winner because it's current standard javascript.

t(3600, true) gives TypeError: string is not a function. Also, a/(d*d) → a/d/d and a-(0|f[b+1]) → 0|a-f[b+1].

@minitech Thanks! I don't know how i missed the d/d. 1. Only the second time, called. I was overriding t 2.Changed it. 3. This is not quite correct. I'm needing the first one. as I'm accessing f[b+1] which can be undefined when exceeding the arrays range.2-(0|undefined /*0*/) //2 wheras 0|(2-undefined /*NaN*/) //0

Oh, in that case, try ~~f[b+1].

155 147 characters.
textTime=(t,z,m,x)=>(x=[t/3600,t/60%60,t%60].map((t,i)=>(!z||t|0)&&~~t+["hrs","min","sec"][i]+"."||0).slice(0,2+!m),(z?x.filter(x=>x):x).join(" "))

If the parameters made a little more sense, yes, it would be fewer.
Non-ES6, changing the name and using globals like @C5H8NNaO4 did, at 183 characters:
function t(t,z,m){return(x=[t/3600,t/60%60,t%60].map(function(t,i){return(!z||t|0)&&~~t+["hrs","min","sec"][i]+"."||0}).slice(0,2+!m),(z?x.filter(function(x){return x}):x).join(" "))}

How do i run it ?

@C5H8NNaO4: The latest Firefox.

those are like c# lamdas right?  are they (will they be) standard javascript?

@AwokeKnowing: Yes, they’re part of ES6, the next/“current” standard. You can already use them in Firefox. In other browsers, it’s function t(t,z,m,x){return x=(m?[t/60,t%60]:[t/3600,t/60%60,t%60]).map(function(t,i){return(!z||t|0)&&~~t+["sec","min","hrs"][2-i-~~m]+"."||0}),(z?x.filter(function(x){return x;}):x).join(" ")} (193).

I got SyntaxError: Unexpected token ILLEGAL when I just pasted this version into chrome (the console)

@AwokeKnowing: Copying that adds some silly carriage returns or something. I’ll add it to the answer.

t(3600,1,1) //"60min." shouldn't that be "1hrs."?

@C5H8NNaO4: Ah, yes, there were more details added to the question. I originally interpreted “show up to minutes” as “show minutes and seconds”, not “show hours and minutes”. Give me a minute…

165 chars
function x(T, Z, M){
f=Math.round;h=T/3600;m=h%1*60;s=m%1*60;
r=f(h)+'hrs '+f(m)+'min '+f(s)+'sec'
Z?r=r.replace(/0\w+/g,''):0
M?r=r.replace(/\d+sec/,''):0
return r}

I just realized that this solution doesn't work for T<60, so I added a few characters and that fixed it (see below):
167 chars
function x(T, Z, M){
f=Math.round;h=T/3600;m=h%1*60;s=m%1*60;
r=f(h)+'hrs '+f(~~m)+'min '+f(s)+'sec'
Z?r=r.replace(/0\w+/g,''):0
M?r=r.replace(/\d+sec/,''):0
return r}

If you don't care about getting the rounding quite right:
149 chars
function x(T, Z, M){
h=T/3600;m=h%1*60;s=m%1*60;
r=~~h+'hrs '+~~m+'min '+~~s+'sec'
Z?r=r.replace(/0\w+/g,''):0
M?r=r.replace(/\d+sec/,''):0
return r}

Dat modulus though.. amazing!

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


text:
BrainF***-optimize a series of numbers
An often-used trick in BF-golfing is something I call "multiply then add."  Let's say that you want to initialize the memory to contain a series of numbers, like 87 75 68 96.  The simplest way to do this is to simply write out a long series of 326 + signs.  A better method, however is below.
++++++++++[>+++++++++>+++++++>+++++++>++++++++++<<<<-]>--->+++++>-->----

(I write this by hand, I hope it works correctly)
The basic idea is that you create a series of numbers (9,7,7,10), multiply them by a constant (10), and then add another series of numbers (-3,5,-2,-4).  My invented form of notation writes this as (10;9,7,7,10;-3,5,-2,-4) which directly corresponds to the BF code.
There is a lot of importance placed in how the numbers are divided.  If I were to pick a larger constant, then the first series of numbers would be much smaller, yet there will tend to be larger remainders after the multiplication.  If I were to pick a smaller constant, then the first series would be larger, but the second series smaller.
Your goal is to write the shortest program to find the best possible way to write a series of numbers in BF using the multiply-then-add strategy.
Your program will recieve a series of non-negative integers.  It should find the best way to generate these numbers.
For example, lets say that it receives the series (3,16,8,4), as an easy example.  The best way to represent this is by the set of numbers (4;1,4,2,1;-1,0,0,0), which is what your program is expected to output (the exact formatting isn't as important).  This corresponds to the following program:
++++[>+>++++>++>+<<<<-]>->>>

Isn't this just a slight specialisation of BF golfer?

Python, 205 characters
def o(l):
    d=lambda l,a:[(d+1,m-a)if m>a/2 else(d,m) for d,m in(divmod(x,a)for x in l)]
    a,x=min((a+sum(abs(x)+abs(y)for x,y in d(l,a)),a,d(l,a))for a in range(1,max(l)+1))[1:]
    return [a]+zip(*x)

Examples:
>>> o([3,16,8,4])
[4, (1, 4, 2, 1), (-1, 0, 0, 0)]
>>> o([87,75,68,96])
[11, (8, 7, 6, 9), (-1, -2, 2, -3)]
>>> o([4,4,4])
[4, (1, 1, 1), (0, 0, 0)]
>>> o([1,2,3,4,5,6,7,8])
[4, (0, 0, 1, 1, 1, 1, 2, 2), (1, 2, -1, 0, 1, 2, -1, 0)]

As a bonus for a very long solution, the BF formater:
def bf(l):
    N,f,s=o(l)
    return ('%s[%s%s-]%s'%(N*'+',
                           ''.join('>' + x*'+' for x in f),
                           ''.join('<' for _ in f),
                           ''.join('>' + abs(x)*('+' if x>0 else '-')for x in s)))

>>> bf([3,16,8,4])
'++++[>+>++++>++>+<<<<-]>->>>'

GolfScript, 74 65 characters
:f$-1=),{[..{1${\2$*-.abs 2$+[@@]}++\),%$0=}+f%{(@+\}%@\+]}%$0=1=

A quite long golfscript solution which simply tries lots of combinations of numbers and takes the shortest representation.
Input is the list of numbers on the stack and output a list of the final numbers (grouped differently compared with the question - constant, tuples of [factor, addon])
Examples:
{
  :f$-1=),{[..{1${\2$*-.abs 2$+[@@]}++\),%$0=}+f%{(@+\}%@\+]}%$0=1=
}:C;

[3 16 8 4] C p             # -> [4 [1 -1] [4 0] [2 0] [1 0]]
[87 75 68 96] C p          # -> [11 [8 -1] [7 -2] [6 2] [9 -3]]
[1 2 3 4 5 6 7 8] C p      # -> [4 [0 1] [0 2] [1 -1] [1 0] [1 1] [1 2] [2 -1] [2 0]]
[5 5 5] C p                # -> [5 [1 0] [1 0] [1 0]]

Javascript 244 characters
function b(c){function e(f,c){n=m.abs;return n(f)+n(c)}a=0;m=Math;for(i=1;i<m.max.apply(null,c);i++)x=[],y=c.map(function(c){r=c/i|0;d=c%i;d=d>i/2?(r++,d-i):d;x.push(d);return r}),l=i+y.reduce(e)+x.reduce(e),a=!a||l<a[0]?[l,i,y,x]:a;return a};

Examples (first digit in output is total program length):
> b([3,16,8,4])
[13, 4, [1, 4, 2, 1], [-1, 0 0 0]]

> b([87,75,68,96])
[49, 11, [8, 7, 6, 9], [-1, 2, 2, -3]]

I think with "=>" syntax coming soon, I could likely condense further. I wish I was better at BF, I think a solution in BF would be interesting as well.
Solution before condensed:
function b(s){
    a = 0;
    m = Math;
    for(i=1; i<m.max.apply(null, s); i++) {
        x = [];
        y = s.map(function(n) {
            r = n/i|0;
            d = n%i;

            d = d > i/2 ? (r++, d-i) : d;
            x.push(d);
            return r;
        });

        l=i+y.reduce(c)+x.reduce(c);
        a = !a || l < a[0] ? [l,i,y,x] : a;
    }
    function c(g, h) {
        n = m.abs;
        return n(g)+n(h);
    }

    return a;
}

Then ran through google closure compiler to condense to a single line.


text:
Implement division using only addition
There is a question on the site that asks to implement division without using division.
In my case, I am asking you to do the same, but only using addition.
What this means is basically: addition is the only operator or function allowed that operates on numbers and returns other numbers (i.e. no subtraction, multiplication, exponentiation, bitwise inversion, etc.). Stuff like if statements, assignment and comparison operators, and for loops are still allowed, provided that within those, you still only use addition.
Your task is to build a function divide(a, b) that takes two positive integers a and b and returns the result of a being divided by b and rounded toward zero, but using addition and no other arithmetical operators, and no other data constructs besides numbers.
The code that wins will be the one that requires the fewest addition operations to be performed over the set of inputs where a varies from 1 to 200 and b varies from 1 to a.
To keep track of this, you can build an alternate version of your code that replaces every instance of a + b with add(a, b) and program add to increment a global add_used variable as well as returning the sum of the two numbers.

I'm probably not going to accept any answer, just because there were too many loopholes in this question for it to be meaningful.

eBusiness answered the challenge well, imho. A lookup table solves the challenge without any additions. Yes, it's a bit humorous, but what the heck? I also like Johannes Kuhn's approach.  You moved the goalposts to disqualify his entry. That, to me, was unfair.

I agree that he answered the challenge well, and I upvoted his answer for that. But it feels wrong to accept an answer just because the goalposts were incorrectly placed in the first place.

You managed it to disqualify 2 of my answers. Ok, the first one used the division function (which was not an operator at that time), so better leave that deleted.

Writing rules is hard, these rules in particular contain incentive to avoid additions at all costs.
Is there a prize for the most ridiculous answer?
JavaScript - 0 additions
Now with fallback method that does a hulking solution for larger a's and b's, and a slightly more compact structure in order not to bust the character limit. (Pfff, 30000 characters. What is this? Twitter?) Still no additions in the measured scope.
function divide(a,b){
    if(a<b){
        return 0
    }
    if(b==1){
        return a
    }
    if(b==2){
        if(a<4){return 1}
        if(a<6){return 2}
        if(a<8){return 3}
        if(a<10){return 4}
        if(a<12){return 5}
        if(a<14){return 6}
        if(a<16){return 7}
        if(a<18){return 8}
        if(a<20){return 9}
        if(a<22){return 10}
        if(a<24){return 11}
        if(a<26){return 12}
        if(a<28){return 13}
        if(a<30){return 14}
        if(a<32){return 15}
        if(a<34){return 16}
        if(a<36){return 17}
        if(a<38){return 18}
        if(a<40){return 19}
        if(a<42){return 20}
        if(a<44){return 21}
        if(a<46){return 22}
        if(a<48){return 23}
        if(a<50){return 24}
        if(a<52){return 25}
        if(a<54){return 26}
        if(a<56){return 27}
        if(a<58){return 28}
        if(a<60){return 29}
        if(a<62){return 30}
        if(a<64){return 31}
        if(a<66){return 32}
        if(a<68){return 33}
        if(a<70){return 34}
        if(a<72){return 35}
        if(a<74){return 36}
        if(a<76){return 37}
        if(a<78){return 38}
        if(a<80){return 39}
        if(a<82){return 40}
        if(a<84){return 41}
        if(a<86){return 42}
        if(a<88){return 43}
        if(a<90){return 44}
        if(a<92){return 45}
        if(a<94){return 46}
        if(a<96){return 47}
        if(a<98){return 48}
        if(a<100){return 49}
        if(a<102){return 50}
        if(a<104){return 51}
        if(a<106){return 52}
        if(a<108){return 53}
        if(a<110){return 54}
        if(a<112){return 55}
        if(a<114){return 56}
        if(a<116){return 57}
        if(a<118){return 58}
        if(a<120){return 59}
        if(a<122){return 60}
        if(a<124){return 61}
        if(a<126){return 62}
        if(a<128){return 63}
        if(a<130){return 64}
        if(a<132){return 65}
        if(a<134){return 66}
        if(a<136){return 67}
        if(a<138){return 68}
        if(a<140){return 69}
        if(a<142){return 70}
        if(a<144){return 71}
        if(a<146){return 72}
        if(a<148){return 73}
        if(a<150){return 74}
        if(a<152){return 75}
        if(a<154){return 76}
        if(a<156){return 77}
        if(a<158){return 78}
        if(a<160){return 79}
        if(a<162){return 80}
        if(a<164){return 81}
        if(a<166){return 82}
        if(a<168){return 83}
        if(a<170){return 84}
        if(a<172){return 85}
        if(a<174){return 86}
        if(a<176){return 87}
        if(a<178){return 88}
        if(a<180){return 89}
        if(a<182){return 90}
        if(a<184){return 91}
        if(a<186){return 92}
        if(a<188){return 93}
        if(a<190){return 94}
        if(a<192){return 95}
        if(a<194){return 96}
        if(a<196){return 97}
        if(a<198){return 98}
        if(a<200){return 99}
        if(a<202){return 100}
    }
    if(b==3){
        if(a<6){return 1}
        if(a<9){return 2}
        if(a<12){return 3}
        if(a<15){return 4}
        if(a<18){return 5}
        if(a<21){return 6}
        if(a<24){return 7}
        if(a<27){return 8}
        if(a<30){return 9}
        if(a<33){return 10}
        if(a<36){return 11}
        if(a<39){return 12}
        if(a<42){return 13}
        if(a<45){return 14}
        if(a<48){return 15}
        if(a<51){return 16}
        if(a<54){return 17}
        if(a<57){return 18}
        if(a<60){return 19}
        if(a<63){return 20}
        if(a<66){return 21}
        if(a<69){return 22}
        if(a<72){return 23}
        if(a<75){return 24}
        if(a<78){return 25}
        if(a<81){return 26}
        if(a<84){return 27}
        if(a<87){return 28}
        if(a<90){return 29}
        if(a<93){return 30}
        if(a<96){return 31}
        if(a<99){return 32}
        if(a<102){return 33}
        if(a<105){return 34}
        if(a<108){return 35}
        if(a<111){return 36}
        if(a<114){return 37}
        if(a<117){return 38}
        if(a<120){return 39}
        if(a<123){return 40}
        if(a<126){return 41}
        if(a<129){return 42}
        if(a<132){return 43}
        if(a<135){return 44}
        if(a<138){return 45}
        if(a<141){return 46}
        if(a<144){return 47}
        if(a<147){return 48}
        if(a<150){return 49}
        if(a<153){return 50}
        if(a<156){return 51}
        if(a<159){return 52}
        if(a<162){return 53}
        if(a<165){return 54}
        if(a<168){return 55}
        if(a<171){return 56}
        if(a<174){return 57}
        if(a<177){return 58}
        if(a<180){return 59}
        if(a<183){return 60}
        if(a<186){return 61}
        if(a<189){return 62}
        if(a<192){return 63}
        if(a<195){return 64}
        if(a<198){return 65}
        if(a<201){return 66}
    }
    if(b==4){
        if(a<8){return 1}
        if(a<12){return 2}
        if(a<16){return 3}
        if(a<20){return 4}
        if(a<24){return 5}
        if(a<28){return 6}
        if(a<32){return 7}
        if(a<36){return 8}
        if(a<40){return 9}
        if(a<44){return 10}
        if(a<48){return 11}
        if(a<52){return 12}
        if(a<56){return 13}
        if(a<60){return 14}
        if(a<64){return 15}
        if(a<68){return 16}
        if(a<72){return 17}
        if(a<76){return 18}
        if(a<80){return 19}
        if(a<84){return 20}
        if(a<88){return 21}
        if(a<92){return 22}
        if(a<96){return 23}
        if(a<100){return 24}
        if(a<104){return 25}
        if(a<108){return 26}
        if(a<112){return 27}
        if(a<116){return 28}
        if(a<120){return 29}
        if(a<124){return 30}
        if(a<128){return 31}
        if(a<132){return 32}
        if(a<136){return 33}
        if(a<140){return 34}
        if(a<144){return 35}
        if(a<148){return 36}
        if(a<152){return 37}
        if(a<156){return 38}
        if(a<160){return 39}
        if(a<164){return 40}
        if(a<168){return 41}
        if(a<172){return 42}
        if(a<176){return 43}
        if(a<180){return 44}
        if(a<184){return 45}
        if(a<188){return 46}
        if(a<192){return 47}
        if(a<196){return 48}
        if(a<200){return 49}
        if(a<204){return 50}
    }
    if(b==5){
        if(a<10){return 1}
        if(a<15){return 2}
        if(a<20){return 3}
        if(a<25){return 4}
        if(a<30){return 5}
        if(a<35){return 6}
        if(a<40){return 7}
        if(a<45){return 8}
        if(a<50){return 9}
        if(a<55){return 10}
        if(a<60){return 11}
        if(a<65){return 12}
        if(a<70){return 13}
        if(a<75){return 14}
        if(a<80){return 15}
        if(a<85){return 16}
        if(a<90){return 17}
        if(a<95){return 18}
        if(a<100){return 19}
        if(a<105){return 20}
        if(a<110){return 21}
        if(a<115){return 22}
        if(a<120){return 23}
        if(a<125){return 24}
        if(a<130){return 25}
        if(a<135){return 26}
        if(a<140){return 27}
        if(a<145){return 28}
        if(a<150){return 29}
        if(a<155){return 30}
        if(a<160){return 31}
        if(a<165){return 32}
        if(a<170){return 33}
        if(a<175){return 34}
        if(a<180){return 35}
        if(a<185){return 36}
        if(a<190){return 37}
        if(a<195){return 38}
        if(a<200){return 39}
        if(a<205){return 40}
    }
    if(b==6){
        if(a<12){return 1}
        if(a<18){return 2}
        if(a<24){return 3}
        if(a<30){return 4}
        if(a<36){return 5}
        if(a<42){return 6}
        if(a<48){return 7}
        if(a<54){return 8}
        if(a<60){return 9}
        if(a<66){return 10}
        if(a<72){return 11}
        if(a<78){return 12}
        if(a<84){return 13}
        if(a<90){return 14}
        if(a<96){return 15}
        if(a<102){return 16}
        if(a<108){return 17}
        if(a<114){return 18}
        if(a<120){return 19}
        if(a<126){return 20}
        if(a<132){return 21}
        if(a<138){return 22}
        if(a<144){return 23}
        if(a<150){return 24}
        if(a<156){return 25}
        if(a<162){return 26}
        if(a<168){return 27}
        if(a<174){return 28}
        if(a<180){return 29}
        if(a<186){return 30}
        if(a<192){return 31}
        if(a<198){return 32}
        if(a<204){return 33}
    }
    if(b==7){
        if(a<14){return 1}
        if(a<21){return 2}
        if(a<28){return 3}
        if(a<35){return 4}
        if(a<42){return 5}
        if(a<49){return 6}
        if(a<56){return 7}
        if(a<63){return 8}
        if(a<70){return 9}
        if(a<77){return 10}
        if(a<84){return 11}
        if(a<91){return 12}
        if(a<98){return 13}
        if(a<105){return 14}
        if(a<112){return 15}
        if(a<119){return 16}
        if(a<126){return 17}
        if(a<133){return 18}
        if(a<140){return 19}
        if(a<147){return 20}
        if(a<154){return 21}
        if(a<161){return 22}
        if(a<168){return 23}
        if(a<175){return 24}
        if(a<182){return 25}
        if(a<189){return 26}
        if(a<196){return 27}
        if(a<203){return 28}
    }
    if(b==8){
        if(a<16){return 1}
        if(a<24){return 2}
        if(a<32){return 3}
        if(a<40){return 4}
        if(a<48){return 5}
        if(a<56){return 6}
        if(a<64){return 7}
        if(a<72){return 8}
        if(a<80){return 9}
        if(a<88){return 10}
        if(a<96){return 11}
        if(a<104){return 12}
        if(a<112){return 13}
        if(a<120){return 14}
        if(a<128){return 15}
        if(a<136){return 16}
        if(a<144){return 17}
        if(a<152){return 18}
        if(a<160){return 19}
        if(a<168){return 20}
        if(a<176){return 21}
        if(a<184){return 22}
        if(a<192){return 23}
        if(a<200){return 24}
        if(a<208){return 25}
    }
    if(b==9){
        if(a<18){return 1}
        if(a<27){return 2}
        if(a<36){return 3}
        if(a<45){return 4}
        if(a<54){return 5}
        if(a<63){return 6}
        if(a<72){return 7}
        if(a<81){return 8}
        if(a<90){return 9}
        if(a<99){return 10}
        if(a<108){return 11}
        if(a<117){return 12}
        if(a<126){return 13}
        if(a<135){return 14}
        if(a<144){return 15}
        if(a<153){return 16}
        if(a<162){return 17}
        if(a<171){return 18}
        if(a<180){return 19}
        if(a<189){return 20}
        if(a<198){return 21}
        if(a<207){return 22}
    }
    if(b==10){
        if(a<20){return 1}
        if(a<30){return 2}
        if(a<40){return 3}
        if(a<50){return 4}
        if(a<60){return 5}
        if(a<70){return 6}
        if(a<80){return 7}
        if(a<90){return 8}
        if(a<100){return 9}
        if(a<110){return 10}
        if(a<120){return 11}
        if(a<130){return 12}
        if(a<140){return 13}
        if(a<150){return 14}
        if(a<160){return 15}
        if(a<170){return 16}
        if(a<180){return 17}
        if(a<190){return 18}
        if(a<200){return 19}
        if(a<210){return 20}
    }
    if(b==11){
        if(a<22){return 1}
        if(a<33){return 2}
        if(a<44){return 3}
        if(a<55){return 4}
        if(a<66){return 5}
        if(a<77){return 6}
        if(a<88){return 7}
        if(a<99){return 8}
        if(a<110){return 9}
        if(a<121){return 10}
        if(a<132){return 11}
        if(a<143){return 12}
        if(a<154){return 13}
        if(a<165){return 14}
        if(a<176){return 15}
        if(a<187){return 16}
        if(a<198){return 17}
        if(a<209){return 18}
    }
    if(b==12){
        if(a<24){return 1}
        if(a<36){return 2}
        if(a<48){return 3}
        if(a<60){return 4}
        if(a<72){return 5}
        if(a<84){return 6}
        if(a<96){return 7}
        if(a<108){return 8}
        if(a<120){return 9}
        if(a<132){return 10}
        if(a<144){return 11}
        if(a<156){return 12}
        if(a<168){return 13}
        if(a<180){return 14}
        if(a<192){return 15}
        if(a<204){return 16}
    }
    if(b==13){
        if(a<26){return 1}
        if(a<39){return 2}
        if(a<52){return 3}
        if(a<65){return 4}
        if(a<78){return 5}
        if(a<91){return 6}
        if(a<104){return 7}
        if(a<117){return 8}
        if(a<130){return 9}
        if(a<143){return 10}
        if(a<156){return 11}
        if(a<169){return 12}
        if(a<182){return 13}
        if(a<195){return 14}
        if(a<208){return 15}
    }
    if(b==14){
        if(a<28){return 1}
        if(a<42){return 2}
        if(a<56){return 3}
        if(a<70){return 4}
        if(a<84){return 5}
        if(a<98){return 6}
        if(a<112){return 7}
        if(a<126){return 8}
        if(a<140){return 9}
        if(a<154){return 10}
        if(a<168){return 11}
        if(a<182){return 12}
        if(a<196){return 13}
        if(a<210){return 14}
    }
    if(b==15){
        if(a<30){return 1}
        if(a<45){return 2}
        if(a<60){return 3}
        if(a<75){return 4}
        if(a<90){return 5}
        if(a<105){return 6}
        if(a<120){return 7}
        if(a<135){return 8}
        if(a<150){return 9}
        if(a<165){return 10}
        if(a<180){return 11}
        if(a<195){return 12}
        if(a<210){return 13}
    }
    if(b==16){
        if(a<32){return 1}
        if(a<48){return 2}
        if(a<64){return 3}
        if(a<80){return 4}
        if(a<96){return 5}
        if(a<112){return 6}
        if(a<128){return 7}
        if(a<144){return 8}
        if(a<160){return 9}
        if(a<176){return 10}
        if(a<192){return 11}
        if(a<208){return 12}
    }
    if(b==17){
        if(a<34){return 1}
        if(a<51){return 2}
        if(a<68){return 3}
        if(a<85){return 4}
        if(a<102){return 5}
        if(a<119){return 6}
        if(a<136){return 7}
        if(a<153){return 8}
        if(a<170){return 9}
        if(a<187){return 10}
        if(a<204){return 11}
    }
    if(b==18){
        if(a<36){return 1}
        if(a<54){return 2}
        if(a<72){return 3}
        if(a<90){return 4}
        if(a<108){return 5}
        if(a<126){return 6}
        if(a<144){return 7}
        if(a<162){return 8}
        if(a<180){return 9}
        if(a<198){return 10}
        if(a<216){return 11}
    }
    if(b==19){
        if(a<38){return 1}
        if(a<57){return 2}
        if(a<76){return 3}
        if(a<95){return 4}
        if(a<114){return 5}
        if(a<133){return 6}
        if(a<152){return 7}
        if(a<171){return 8}
        if(a<190){return 9}
        if(a<209){return 10}
    }
    if(b==20){
        if(a<40){return 1}
        if(a<60){return 2}
        if(a<80){return 3}
        if(a<100){return 4}
        if(a<120){return 5}
        if(a<140){return 6}
        if(a<160){return 7}
        if(a<180){return 8}
        if(a<200){return 9}
        if(a<220){return 10}
    }
    if(b==21){
        if(a<42){return 1}
        if(a<63){return 2}
        if(a<84){return 3}
        if(a<105){return 4}
        if(a<126){return 5}
        if(a<147){return 6}
        if(a<168){return 7}
        if(a<189){return 8}
        if(a<210){return 9}
    }
    if(b==22){
        if(a<44){return 1}
        if(a<66){return 2}
        if(a<88){return 3}
        if(a<110){return 4}
        if(a<132){return 5}
        if(a<154){return 6}
        if(a<176){return 7}
        if(a<198){return 8}
        if(a<220){return 9}
    }
    if(b==23){
        if(a<46){return 1}
        if(a<69){return 2}
        if(a<92){return 3}
        if(a<115){return 4}
        if(a<138){return 5}
        if(a<161){return 6}
        if(a<184){return 7}
        if(a<207){return 8}
    }
    if(b==24){
        if(a<48){return 1}
        if(a<72){return 2}
        if(a<96){return 3}
        if(a<120){return 4}
        if(a<144){return 5}
        if(a<168){return 6}
        if(a<192){return 7}
        if(a<216){return 8}
    }
    if(b==25){
        if(a<50){return 1}
        if(a<75){return 2}
        if(a<100){return 3}
        if(a<125){return 4}
        if(a<150){return 5}
        if(a<175){return 6}
        if(a<200){return 7}
        if(a<225){return 8}
    }
    if(b==26){
        if(a<52){return 1}
        if(a<78){return 2}
        if(a<104){return 3}
        if(a<130){return 4}
        if(a<156){return 5}
        if(a<182){return 6}
        if(a<208){return 7}
    }
    if(b==27){
        if(a<54){return 1}
        if(a<81){return 2}
        if(a<108){return 3}
        if(a<135){return 4}
        if(a<162){return 5}
        if(a<189){return 6}
        if(a<216){return 7}
    }
    if(b==28){
        if(a<56){return 1}
        if(a<84){return 2}
        if(a<112){return 3}
        if(a<140){return 4}
        if(a<168){return 5}
        if(a<196){return 6}
        if(a<224){return 7}
    }
    if(b==29){
        if(a<58){return 1}
        if(a<87){return 2}
        if(a<116){return 3}
        if(a<145){return 4}
        if(a<174){return 5}
        if(a<203){return 6}
    }
    if(b==30){
        if(a<60){return 1}
        if(a<90){return 2}
        if(a<120){return 3}
        if(a<150){return 4}
        if(a<180){return 5}
        if(a<210){return 6}
    }
    if(b==31){
        if(a<62){return 1}
        if(a<93){return 2}
        if(a<124){return 3}
        if(a<155){return 4}
        if(a<186){return 5}
        if(a<217){return 6}
    }
    if(b==32){
        if(a<64){return 1}
        if(a<96){return 2}
        if(a<128){return 3}
        if(a<160){return 4}
        if(a<192){return 5}
        if(a<224){return 6}
    }
    if(b==33){
        if(a<66){return 1}
        if(a<99){return 2}
        if(a<132){return 3}
        if(a<165){return 4}
        if(a<198){return 5}
        if(a<231){return 6}
    }
    if(b==34){
        if(a<68){return 1}
        if(a<102){return 2}
        if(a<136){return 3}
        if(a<170){return 4}
        if(a<204){return 5}
    }
    if(b==35){
        if(a<70){return 1}
        if(a<105){return 2}
        if(a<140){return 3}
        if(a<175){return 4}
        if(a<210){return 5}
    }
    if(b==36){
        if(a<72){return 1}
        if(a<108){return 2}
        if(a<144){return 3}
        if(a<180){return 4}
        if(a<216){return 5}
    }
    if(b==37){
        if(a<74){return 1}
        if(a<111){return 2}
        if(a<148){return 3}
        if(a<185){return 4}
        if(a<222){return 5}
    }
    if(b==38){
        if(a<76){return 1}
        if(a<114){return 2}
        if(a<152){return 3}
        if(a<190){return 4}
        if(a<228){return 5}
    }
    if(b==39){
        if(a<78){return 1}
        if(a<117){return 2}
        if(a<156){return 3}
        if(a<195){return 4}
        if(a<234){return 5}
    }
    if(b==40){
        if(a<80){return 1}
        if(a<120){return 2}
        if(a<160){return 3}
        if(a<200){return 4}
        if(a<240){return 5}
    }
    if(b==41){
        if(a<82){return 1}
        if(a<123){return 2}
        if(a<164){return 3}
        if(a<205){return 4}
    }
    if(b==42){
        if(a<84){return 1}
        if(a<126){return 2}
        if(a<168){return 3}
        if(a<210){return 4}
    }
    if(b==43){
        if(a<86){return 1}
        if(a<129){return 2}
        if(a<172){return 3}
        if(a<215){return 4}
    }
    if(b==44){
        if(a<88){return 1}
        if(a<132){return 2}
        if(a<176){return 3}
        if(a<220){return 4}
    }
    if(b==45){
        if(a<90){return 1}
        if(a<135){return 2}
        if(a<180){return 3}
        if(a<225){return 4}
    }
    if(b==46){
        if(a<92){return 1}
        if(a<138){return 2}
        if(a<184){return 3}
        if(a<230){return 4}
    }
    if(b==47){
        if(a<94){return 1}
        if(a<141){return 2}
        if(a<188){return 3}
        if(a<235){return 4}
    }
    if(b==48){
        if(a<96){return 1}
        if(a<144){return 2}
        if(a<192){return 3}
        if(a<240){return 4}
    }
    if(b==49){
        if(a<98){return 1}
        if(a<147){return 2}
        if(a<196){return 3}
        if(a<245){return 4}
    }
    if(b==50){
        if(a<100){return 1}
        if(a<150){return 2}
        if(a<200){return 3}
        if(a<250){return 4}
    }
    if(b==51){
        if(a<102){return 1}
        if(a<153){return 2}
        if(a<204){return 3}
    }
    if(b==52){
        if(a<104){return 1}
        if(a<156){return 2}
        if(a<208){return 3}
    }
    if(b==53){
        if(a<106){return 1}
        if(a<159){return 2}
        if(a<212){return 3}
    }
    if(b==54){
        if(a<108){return 1}
        if(a<162){return 2}
        if(a<216){return 3}
    }
    if(b==55){
        if(a<110){return 1}
        if(a<165){return 2}
        if(a<220){return 3}
    }
    if(b==56){
        if(a<112){return 1}
        if(a<168){return 2}
        if(a<224){return 3}
    }
    if(b==57){
        if(a<114){return 1}
        if(a<171){return 2}
        if(a<228){return 3}
    }
    if(b==58){
        if(a<116){return 1}
        if(a<174){return 2}
        if(a<232){return 3}
    }
    if(b==59){
        if(a<118){return 1}
        if(a<177){return 2}
        if(a<236){return 3}
    }
    if(b==60){
        if(a<120){return 1}
        if(a<180){return 2}
        if(a<240){return 3}
    }
    if(b==61){
        if(a<122){return 1}
        if(a<183){return 2}
        if(a<244){return 3}
    }
    if(b==62){
        if(a<124){return 1}
        if(a<186){return 2}
        if(a<248){return 3}
    }
    if(b==63){
        if(a<126){return 1}
        if(a<189){return 2}
        if(a<252){return 3}
    }
    if(b==64){
        if(a<128){return 1}
        if(a<192){return 2}
        if(a<256){return 3}
    }
    if(b==65){
        if(a<130){return 1}
        if(a<195){return 2}
        if(a<260){return 3}
    }
    if(b==66){
        if(a<132){return 1}
        if(a<198){return 2}
        if(a<264){return 3}
    }
    if(b==67){
        if(a<134){return 1}
        if(a<201){return 2}
    }
    if(b==68){
        if(a<136){return 1}
        if(a<204){return 2}
    }
    if(b==69){
        if(a<138){return 1}
        if(a<207){return 2}
    }
    if(b==70){
        if(a<140){return 1}
        if(a<210){return 2}
    }
    if(b==71){
        if(a<142){return 1}
        if(a<213){return 2}
    }
    if(b==72){
        if(a<144){return 1}
        if(a<216){return 2}
    }
    if(b==73){
        if(a<146){return 1}
        if(a<219){return 2}
    }
    if(b==74){
        if(a<148){return 1}
        if(a<222){return 2}
    }
    if(b==75){
        if(a<150){return 1}
        if(a<225){return 2}
    }
    if(b==76){
        if(a<152){return 1}
        if(a<228){return 2}
    }
    if(b==77){
        if(a<154){return 1}
        if(a<231){return 2}
    }
    if(b==78){
        if(a<156){return 1}
        if(a<234){return 2}
    }
    if(b==79){
        if(a<158){return 1}
        if(a<237){return 2}
    }
    if(b==80){
        if(a<160){return 1}
        if(a<240){return 2}
    }
    if(b==81){
        if(a<162){return 1}
        if(a<243){return 2}
    }
    if(b==82){
        if(a<164){return 1}
        if(a<246){return 2}
    }
    if(b==83){
        if(a<166){return 1}
        if(a<249){return 2}
    }
    if(b==84){
        if(a<168){return 1}
        if(a<252){return 2}
    }
    if(b==85){
        if(a<170){return 1}
        if(a<255){return 2}
    }
    if(b==86){
        if(a<172){return 1}
        if(a<258){return 2}
    }
    if(b==87){
        if(a<174){return 1}
        if(a<261){return 2}
    }
    if(b==88){
        if(a<176){return 1}
        if(a<264){return 2}
    }
    if(b==89){
        if(a<178){return 1}
        if(a<267){return 2}
    }
    if(b==90){
        if(a<180){return 1}
        if(a<270){return 2}
    }
    if(b==91){
        if(a<182){return 1}
        if(a<273){return 2}
    }
    if(b==92){
        if(a<184){return 1}
        if(a<276){return 2}
    }
    if(b==93){
        if(a<186){return 1}
        if(a<279){return 2}
    }
    if(b==94){
        if(a<188){return 1}
        if(a<282){return 2}
    }
    if(b==95){
        if(a<190){return 1}
        if(a<285){return 2}
    }
    if(b==96){
        if(a<192){return 1}
        if(a<288){return 2}
    }
    if(b==97){
        if(a<194){return 1}
        if(a<291){return 2}
    }
    if(b==98){
        if(a<196){return 1}
        if(a<294){return 2}
    }
    if(b==99){
        if(a<198){return 1}
        if(a<297){return 2}
    }
    if(b==100){
        if(a<200){return 1}
        if(a<300){return 2}
    }
    if(b<=200 && a<=200){
        return 1
    }
    var result=0
    var counter=b
    for(;a>=counter;counter=add(counter,b)){
        result=add(result,1)
    }
    return result
}

+1 Nice job. Did not thought about this way.

Your answer resembles Mechanical Snail's answer to the division by 3 problem.

Your prize is an upvote. However, I am still looking for an answer to accept.

Ok, now we have a tie. Who wins? @JoeZ. You should accept the answer with has the minimum additions.

@JohannesKuhn Your solution waste energy on also being able to solve divisions outside the scope of the question. I think the dedicated nature of my answer gotta count for something.

Well, actually this one produces incorrect results. If I feed it the input (300, 25) it will return 8 instead of 12.

You could, of course, do what Mechanical Snail did and create a script that generates a terabytes-long program that encodes all possible inputs. I might accept that one.

@JoeZ. Gotta go to bed now, but if you want extrametric ability I guess I can hack on a solution that use additions outside the measured scope, my score would still be zero.

@JoeZ. Given that your question specifically says that a will vary from 1 to 200, you can't disqualify this answer based on its inability to work outside that range. I'd accept this answer.

My question doesn't limit inputs from a from 1 to 200, it only says it will judge the score based on the total additions from that range of inputs. It still has to work for integers above 200.

For example, the current edition of the answer does just that.

@JoeZ. If you specify a range of valid inputs in the question, the answers only need to satisfy those. If it needs to work for larger integers, you should not have put the limit in the question.

I didn't specify a range of valid inputs; I specified a range of inputs that would be tested.

In this case, you did not test the input (300,25). Who said that it does not work? (No, don't test it, the rules specify the range that should be tested).

@JoeZ. If you claim that ANY integer has to work you will invalidate many answers that does not handle Integers >= 2^32. So why not set the limit to 255? Or 2^(8*2^40)-1 (Integer with 1 TB size)?

@ JohannesKuhn: I misspoke. By "tested" I meant "have its additions counted".

Tcl, 0 additions
proc divide {a b} {
    set sa [string repeat . $a]
    set sb [string repeat . $b]
    set sr ""
    while 1 {
        append sc $sb
        if {[string le $sc]>[string le $sa]} break
        append sr .
    }
    return [string le $sr]
}

Why not use strings?

Alright, give me some time to revise the question statement.

Hey, too many loopholes.

This one is pretty clever, actually.

This looks good to me.  Append is akin to addition, but it is not quite the same.  I Joined lists, using a similar logic based on tallies.

Haskell 0 additions, 29 bytes
n/m=[i|i<-[0..],_<-[1..m]]!!n

this redefines the division operator (/). it works by making a list of 0 to infinity where each item is repeated m times, and then choosing the nth element of the list (using a 0-based index).

Hey, can you add a description of what this code does?

if this was code golf, you would have surely won..

What about using ([0..]>>=replicate m)!!n. it's almost the same

Use this implementation in java, 199206 additions
public int divide(int a, int b){
    int counter = 0;
    int c = 0;
    if(b==1){
        return a;
    }
    if(a==b){
        return 1;
    }
    else{
        boolean done = false;
        while(!done){
            c = add(c, b);
            if(a<c){
                done = true;
            }
            counter = add(counter,1);
        }
        return counter;

    }
}

Following are the helper functions
public static void main(String[] args) {
    Main main = new Main();

    for(int a = 1; a<=200; a++){
        for(int b=1;b<=a;b++){
            main.divide(a, b);
        }
    }

    System.out.println("Number of additions: "+numberOfAdds);
}

public int add(int a, int b){
    numberOfAdds++;
    return (a+b);
}

yes, thanks for pointing out, corrected it in the answer

Python - 0 additions
from itertools import repeat, count

def divide(a, b):
    i = repeat(0, a)
    try:
        for j in count():
            for k in repeat(0, b):
                next(i)
    except:
        return j

This uses an iterator of length a, and consumes it in groups of b until StopIteration is raised. At this point j contains the result.

My solution is C/C++ code and it makes many additions (200402), but anyway...
#include <iostream>

int total = 0;

int sum(int a, int b)
{
    ++total;
    return a + b;
}

int divide(int a, int b)
{
    int x = 1;
    if (a < b)
        return 0;
    else
        return sum(x, divide(sum(a, -b), b));
}

int main()
{
    for (int i = 1; i <= 200; ++i)
        for (int j = 1; j <= 200; ++j)
        {
            if (divide(i, j) != (i / j))
                std::cout << "Failure: a=" << i << " b=" << j << "\n";
        }

    std::cout << "Total additions: " << total << std::endl;
    system("pause");
}

And the output is:
Total additions: 200402
Press any key to continue . . .

Python, 320703 additions
def divide(a, b):
    quotient = 0
    c = 0
    d = 0
    while add(d, b) <= a:
        c = add(c, 1)
        d = add(d, b)
    return c

As always, a last-place reference answer. This simply adds 1 to a "quotient" and b to a "remultiplication" variable until it hits a.
Here is the debugging code:
add_used = 0

def add(a, b):
    global add_used
    add_used += 1
    return a + b

for a in range(1, 201):
    for b in range(1, a+1):
        print "%d / %d = %d" % (a, b, divide(a, b))

print "Additions used:", add_used

Tcl, 0 additions.
Well, I had to find a way that does not use other data structures but is still not what you want:
# coroutine counter.
proc ccnt {} {yield [info level]; ccnt}
# add implementation without add.
proc cadd {a b} {
    set last 2
    coroutine cadda ccnt
    coroutine caddb ccnt
    while {[cadda]<=$a} {}
    while {[caddb]<=$b} {set last [cadda]}
    rename cadda {}
    rename caddb {}
    return $last
}

proc divide {a b {c 0}} {
    if {$c == 0} {set c $b} {set c [cadd $b $c]}
    if {$c>$a} {tailcall info level}
    divide $a $b $c
}

Uses the current stack size of different green threads.

Nope, this is perfect.

Really? I think I'll rewrite it a bit using coroutines.

And again: score 0

Dammit D: [Well, that's as far as I'm willing to go :<]

+1 for you as well, overflowing the stack for relatively trivial problems that happen to lie outside the area that is being judged is really in the spirit of totally ****** ** solutions!

Mathematica 100201 additions
This adds the divisor, b, to c (which is initialized at 0) as long as the running total is less than or equal to the dividend, a. It also appends the current value of c to a list, t, without performing any arithmetic operation.
When the While loop terminates the function outputs the length of t, which will correspond exactly to the quotient of integer division.
Thus the number of additions for any given divide[a,b] will equal precisely the quotient.
100201 is the sum of the quotients in the 200 by 200 table.  That's how many times c was incremented by b. No other additions were required.  Only positive integers were used.
divide[a_, b_] := Module[{c = 0, t = {}}, While[c <= a, t = Append[t, c]; c += b];
Length[Rest@t]]

It's more efficient to make a lookup table, after which each search will be almost instantaneous.
n = 200;
d[a_, b_] := Module[{c = 0, t = {}}, While[c <= a, t = Append[t, c]; c += b];
Length[Rest@t]]
quotients = PadRight[#, n] & /@ Table[d[i, j], {i, 1, n}, {j, 1, i}];
divide[a_, b_] := quotients[[a, b]]

Usage
divide[97, 13]

7

So more or less my string based solution? Ohh, and can you explain the n++ thing? Looks like addition for me.

Yeah, the successor function counts as addition, without which it's not allowed.

@Johannes Kuhn. I removed the n++, which was totally unnecessary.  From what I can tell, (I don't know TCL), my solution is like yours, but stores the elements together in multi-sets rather then in strings.

What about no other data constructs besides numbers?

@Ugoren Don't you think a base one number system qualifies as being about numbers? The arguable issue, I think, is whether or not joining constitutes adding.

Simple: They count as addition if they are not an other data structure than numbers.

I completely rewrote the function, using only positive integers.

C++ ,100201
for(int a = 1; a<=200; a++){
        for(int b=1;b<=a;b++){
    iter1 = iter2 = b;
cout<<a<<" "<<b<<endl;

c1 =0;
while(iter1 <= a)
{
    iter1 = iter1 + iter2;
    c1 ++;
    nadd++;
}
cout<<"Quotient : "<<c1;
cout<<" Remainder :"<<a - (iter1 - iter2)<<endl;
}
}
cout<<"total of add "<<nadd;

If a < b the result should be 0, not an error.

@JoeZ.  ok thanks , is it fine now?

break should be continue.

inner loop should break I think , because once a < b then inner loop is increasing b then you should I do for other b's...actually that is redundant so I should remove that statement, a < b will never happen in this case...

Oh wait, never mind, I see what you mean. (I got confused by the order of the numbers.)

R - 0 addition
divide<-function(a,b){
    options(warn=-1)
    A<-matrix(1:b,nrow=a,ncol=1)
    length(split(A,A)[[b]])
    }

Uses R vector recycling.
Second line creates a matrix of length a populated by a vector of length bwhich is recycled until reaching length a.
Third line split the matrix according to its value and return the length of the last element (hence the result of the integer division of a by b).
Populating a matrix with a vector which length is not a multiple of the length of the matrix throws a warning but if we suppress warning beforehand (line 1) it works.
To give a concrete example if we divide 5 by 3, A will be a vector containing 1 2 3 1 2 (i. e. 1 2 3 recycled to a length 5). The result of the splitting operation will be a list with the first element containing 1 1, the second 2 2 and the third 3 (since there is only one 3 in A). The result is therefore 1.

A Matix sounds like a different data structure than a number.

Ah indeed I missed the part where it was specified that the only data construct allowed was numbers. My bad. I answered after the edit but read the question before :)

In Ruby,
def divide(a,b)
  n, d = 'x' * a, 'x' * b
  l = []
  (l << 'x'; d << 'x' * b) while n.size >= d.size
  l.size
end

I don't know TCL, but I suspect this is the same approach as @Johannes ' (first) answer.

What do the * and << do? I'm not familiar with Ruby.

@Joe: d = 'x' * 5 => "xxxxx".  a << b appends string b to string a.  Here, d = "xxx" and d << 'x' results in d = "xxxx".

Java: 92 987 additions
I use binary recursion, that a/b == 2 * a/(2b) + maybe 1. For that divisor and remainder are needed. There would normally be a subtraction a % (2b) - b, but that is resolved by holding the remainder as (rem, remNegative). And 2b = b+b of course.
static int add_used;

static int add(int a, int b) {
    if (a == 0)
        return b;
    if (b == 0)
        return a;
    ++add_used;
    return a + b;
}

private static class DivRem {
    int div;
    int rem;
    int remNegative;

    DivRem(int div, int rem) {
        this.div = div;
        this.rem = rem;
    }
}

public static int divide(int a, int b) {
    add_used = 0;
    return divrem(a, b).div;
}

public static DivRem divrem(int a, int b) {
    if (b > a) {
        return new DivRem(0, a);
    }
    DivRem dr = divrem(a, add(b, b));
    dr.div = add(dr.div, dr.div);
    if (dr.rem >= add(b, dr.remNegative)) {
        dr.div = add(dr.div, 1);
        //dr.rem = add(dr.rem,  -b);
        dr.remNegative = add(dr.remNegative,  b);
    }
    return dr;
}

private static void test(int a, int b) {
    boolean okay = a/b == divide(a, b);
    System.out.printf("%d / %d = %d :: %d : #%d  %s%n", a, b, a/b,
        divide(a, b), add_used, okay);
}

public static void main(String[] args) {
   //test(2352, 324);
   int n = 0;
   for (int a = 1; a <= 200; ++a) {
       for (int b = 1; b <= a; ++b) {
           //test(a, b);
           divide(a, b);
           n += add_used;
       }
   }
   System.out.println("Additions: " + n);
}

And how many divisions does it use?

@Doorknob 92987 (did not see the for-for).

One remark: this does count neither 0+x nor x+0: so ~100k additions.

//a lies between 1 and 200, b lies between 1 and a.

int divide(int a,int b){
int x=a,y=b;
int count=1;
while(y<x){
y+=y;
count++;
}
return count;
}

And how many additions are that?

C# - 0 additions
using System.Collections.Generic;
using System.Linq;

static int Divide(int a, int b)
{
    var ints = new List<int>(a);
    while (ints.Count < a)
        ints.AddRange(Enumerable.Range(1, b));

    return ints.Select((x, i) => x == b && i < a).Count(x => x);
}

Populates a list of integers with 1..b repeated a times. The number of times b appears (except for the occurrence with an index > a) is the result.
I'm not sure if the list is allowed by the rules, but I'm submitting this in the spirit of the other posts which aren't taking the rules all that seriously (after all, not using addition at all is basically bypassing the challenge altogether).

Yeah, following the "spirit" of the challenge was pretty much abandoned by this point.

There is 1 solution out there that takes all the rules seriously and has 0 additions.

@JohannesKuhn: That's debatable. The challenge is to do division using addition. If we don't use addition, we're not really doing the challenge...

C — 85591 Additions
Here we go. I think this might be optimal. It uses a technique of "reverse division" whereby through long multiplication it builds up the largest number q such that q * b <= a, using only + and <=. It is very, very fast.
#include <stdio.h>
#include <assert.h>

// Division function.
q,u,v,z=0;s(a,b){return!a?b:!b?a:(z++,a+b);}
d(a,b,p){if((v=s(b,b))<=a)d(a,v,s(p,p));if((v=s(u,b))<=a)u=v,q=s(p,q);}
divide(a,b){u=q=0;d(a,b,1);return q;}

// Test driver.
main(){for(int a=1;a<=200;a++)for(int b=1;b<=a;b++)assert(divide(a,b)==q);
printf("%d additions\n",z);}

Notes:

s(a,b) returns the sum a+b and increments counter variable z each time an addition is performed. If either a or b is zero, the unnecessary addition is avoided.
d(a,b,p) is a recursive function to build up the internal portions for comparison and addition. It uses global variables q, u, and v. Maximum recursion depth is the number of bits in a, and the recursion is linear rather than a tree. (Note: the b in this function is the original b multiplied by a power of 2.)
divide(a,b) returns floor(a/b) as required.
Compiles with warnings (because code is golfed). Runs fine.

J, 0 additions, 14 bytes
Inspired by Alexei Kopylov's answer.
f=:[{]#i.@>:@[

Uses no maths at all:
f=:                    NB. define function f
             [         NB. take left argument,
          >:@          NB. increment it,
       i.@             NB. generate the list [0..left arg+1)
     ]#                NB. replicate each item in the list by the right argument
                       NB. (so if ]=2, list becomes 0 0 1 1 2 2 3 3 ...)
   [{                  NB. select the ['th item from that list.


text:
How many pairs?
Inspired by this question
Your challenge is very simple: take input in the form of lookupString string1 string2 ... stringN and output how many pairs of strings there are.
But there's a catch! There are two ways of interpreting "pairs." The first way is combinations. For example,
       1      2     3      4
orange orange apple orange orange

(the first orange is the lookup string) has 3 pairs of oranges, since there is #1 and #3, #3 and #4, and #1 and #4.
The second way of interpreting it is adjacent pairs. For example, the same input would have a result of 1 with this interpretation, since there's only one pair in which both oranges are next to each other. (#3 and #4)
You must write two programs, one with the first interpretation and another with the second. Your score is the sum of the length of the two programs. This is code-golf. Shortest score wins.

"Your score is the length of the two programs combined". combined in which way? Sum of the lengths? L_1 ^ L_2? L_1 * L_2? max(L_1, L_2)?

This question could probably be a lot clearer with rewording to avoid the word "pair". I see six pairs according to the first metric and two pairs according to the second metric.

@Peter The first pear is the search string. Also, it's intentionally confusing :P Why did you think I chose "pear" as my example? :D

All questions on this site should have a clear specification of what constitutes a correct submission.. As things stand you're asking people to read your mind.

@PeterTaylor Meh, okay then, edited

The problem wasn't the use of pear but the lack of explanation of what the lookup string was about, and in particular that it wasn't participating directly in the pairs counted. The numbering makes that much clearer.

J, 24 characters
Anywhere - 14 11
2!+/}.{.=;:

is 2 choose (2!) sum (+/) of the beheading (}.) of the first row (head) ({.) of the self-classification (=) of the words (;:) of its argument
beheading means "drop the first element and return the rest".
Adjanced - 13
+/2*/\}.{.=;:

is the sum (+/) of products (ANDs) within each two-element prefix (2*/\) of the beheading (}.) of the head ({.) of the self-classification (=) of the words (;:) of its argument
ex:
   s=.'pear pear apple pear pear'
   +/#\2}.#~{.=;:s
3
   +/2*/\}.{.=;:s
1

For the first program, the obvious solution (IMO) is shorter 2!+/}.{.=;: at 11 chars

@Volatility thanks - I knew I was something missing but I couldn't find it.

Python 3, 48 + 59 = 107
Anywhere – 48
s,*L=input().split()
c=L.count(s)
print(c*~-c/2)

Adjacent – 59
s,*L=input().split()
print(list(zip(L,L[1:])).count((s,s)))

Ruby, 38 + 45 = 83
Anywhere: 38

-2 chars: Two statements was shorter than one.

l,*a=gets.split
p (n=a.count(l))*~-n/2

Adjacent: 45

-2 chars: Borrowed x==[l,l] from Doorknob.
-2 chars: find_all => select
-12 chars: select => count

l,*a=gets.split
p a.each_cons(2).count([l,l])

Mathematica 33+42 = 75  31+40 = 71
Program 1
Binomial[Count[Rest@#, #〚1〛, 2] &

Example
Binomial[Count[Rest@#, #〚1〛, 2] &[{"orange", "orange", "apple", "orange", "orange"}]

3

Program 2
Count[Partition[Rest@d, 2, 1], {e = #〚1〛, e}] &

Example
Count[Partition[Rest@d,2,1],{e=#〚1〛,e}] &[{"orange","orange","apple","orange", "orange"}]

1

You can replace "[[1]]" by "〚1〛".:)

Thanks. It took me a bit to figure out just how to do that. (Paste double brackets first as regular text then copy and paste into the code.)

Ruby, 46 + 58 = 104
Posting my own solution first as I always do:
Anywhere - 49 46
l,*a=gets.split;p ((1..a.count(l)).inject:*)/2

Adjacent - 65 58
l,*a=gets.split;c=0;a.each_cons(2){|x|c+=1if x==[l,l]};p c

l,*a stolen from daniero :P

Sure your first program is correct? Your own example input gives you 6, while you state the answer is 3.

@daniero Whoops, right. Edited.

R : 82
Anywhere: 38 characters
a=scan(,"")
choose(sum(a[-1]==a[1]),2)

sum(a[-1]==a[1]) returns the number of corresponding item and choose computes the corresponding binomial coefficient.
Adjacent: 44 characters
a=scan(,"")
sum(diff(which(a[-1]==a[1]))==1)

which(a[-1]==a[1]) returns the indices of the matching items, diff computes the difference between those indices and sum(...==1) returns the number of differences being 1 (i. e. the number of pairs of adjacent matching items).

K, 20 + 44 = 64
Anywhere: 20
{-1++/a~\:*a:" "\:x}

Adjacent: 44
{+/min'(*h)~/:/:(2*!-_-(#a)%2)_a:1_h:" "\:x}

.
k){-1++/a~\:*a:" "\:x}"orange orange apple orange orange"
3
k){+/min'(*h)~/:/:(2*!-_-(#a)%2)_a:1_h:" "\:x}"orange orange apple orange orange"
1

JavaScript - 166 chars
F=function(A){return A.match(RegExp(A.split(' ')[0], 'g')).length-1}

G=function(A){C=0;R=A.split(' ').splice(1);for(i=0;i<R.length-1;i++)R[i]==R[i+1]?C++:0;return C}

Edited to be separate functions.

You have to include the S/F/R declaration characters in both snippets...


text:
Random CSS Color code
This blog post about generating random CSS color codes in JavaScript have multiple solutions for generating a random color in JavaScript. The shortest I can find is this:
'#'+(Math.random()*0xffffff).toString(16).slice(-6)

If you are not familiar with CSS color code read documentations here.
Can we do better? What about other languages?

Yours is broken, you're missing a + after the '#'

You can remove the slice by doing this #'+(Math.random()*0xffffff|0).toString(16)

What is the "0xffffff" needed for? I'm not seeing much of a difference in my results without it.

@path411 Theoretically, Math.random().toString(16) can produce a representation with less than 6 hex-digits after the (hexa)decimal point, in which case the function would break. For example, 0.1658172607421875 becomes 0.2A73 in hex.

Linked from Random color generator.

I don't understand why it multiply by 0xffffff. Shouldn't it be 0x1000000 (or $2^{24}$) instead?

PHP 23 bytes
#<?=md5(rand())&ÿÿÿÿÿÿ;

Where ÿ is character 255. Bitwise and will truncate the string returned from md5, which is already in hexadecimal format.

This is one of my favourite solutions on the site.

Three character codes are valid too, so I can save some chars (4095 == 0xfff):
Ruby, 24 23 22 18
'#%03x'%rand(4095)

If I have to use a 6-char one, then:
Ruby, 28 27 26 24 20
Shaved one character off because 8**8-1 == 0xffffff
'#%06x'%rand(8**8-1)

Thanks to chron for the format string, saving 4 chars!

Cheating (with this xkcd strip in mind):
Ruby/JS/Python/Perl/lots more, 6 (or 5)
"#a83"

I assure you, I generated it randomly!
An even cheatier version:
"red"

You don't need parentheses for method calls in Ruby, right?

@Mohsen Yes, but Ruby gets confused and thinks I'm calling to_s on 4095 if I omit them.

You can get it down to 20 with a sprintf format string: '#%06x'%rand(8**8-1)

Javascript
'#'+Math.random().toString(16).substr(2,6)

Just a little shorter at 42.

function randomColor() {
  return '#' + Math.random().toString(16).substr(2, 6);
}

for (var n = 0; n < 16*9; n++) {
  var el = document.createElement('SPAN');
  el.style.backgroundColor = randomColor();
  document.getElementById('demo').appendChild(el);
}
span { width: calc(100%/16);
       height: calc(100vh/9);
       margin-top: -7px;
       display: inline-block;
     }

I'm not sure why this was downvoted. It works fine in every browser I've tested. +1

#'+Math.random().toString(16).slice(-6)

@Mohsen nice! Didn't know slice could do negatives.

Fish 79
vnnnnnnnn
601234567;
>xxxxxxxx<
 89""""""?
 nnABCDEF:
 vv""""""-
 vvoooooo1
 >>>>>>>>^

Not the shortest solution in the world, but it was fun to code :)
It's also not a uniform distribution, but all outputs have a non-zero probability 7 and F are most likely digits.
Outputs:
python fish.py randomColor.fish
07FFF7

python fish.py randomColor.fish
07EFD7

python fish.py randomColor.fish
366F67

python fish.py randomColor.fish
977FD7

python fish.py randomColor.fish
97F7F7

python fish.py randomColor.fish
87F6FF

PowerShell, 28 24 bytes
-4 bytes thanks to @Julian!
"#{0:X6}"-f(random 16MB)

Try it online!

You can omit the -ma as it is implicit and save 4 bytes

Vyxal Ṫ, 8 7 bytes
\#k66ƈṅ

Try it Online!
\#      # Push a #
    6ƈ  # Choose six...
  k6    # Hex digits
      ṅ # Appended to the #

You can outsource a byte to a flag using this method: Try it Online!

@Underslash Nice, thanks!

APL (17)
'#',(⎕D,⎕A)[6?16]

Explanation:

6?16: 6 random numbers from 1 to 16
⎕D,⎕A: the digits (0..9) followed by the alphabet (A..Z) (but only the first 16 values are ever used, i.e. 0..F)
'#',: add a # to the front

6?16 is 6 non-repeating random values though, that narrows the colorspace a bit...

@mniip Yeah, it should be ?6⍴16 instead.

Python 3, 44 bytes
from secrets import*
print("#"+token_hex(3))

Try it online!
Did you know this built-in python module? It was added in python 3.6 to include some random function for paswords (more informations here).
How it works ?
Basicaly, I generate a random 3-bytes long hexadecimal string ... Yeah, that's it.
Python 2, 32 31 bytes
I also have the slightly less elegant :
(also works in Python3 in 34 33 bytes by adding parenthesis for the print function)
print"#%06x"%((id(0)>>16)%8**8)

Try it online!
This one uses the fact that at each execution of the code, python uses an indivdual memory address for each object. This memeory address change at each execution of the program. As the last 16 bits of this id are not random, I shifted the result before using a modulo to have the right number of bits
Thanks to pxeger for -1 bytes

You can use id(0) for -1 byte, though I'm not sure relying on ASLR alone is necessarily a valid random source. (Python doesn't "assign an id number", it uses the memory address of the object, which is assigned by the kernel, and is typically only a bit random, so it's really only suitable for seeding a PRNG)

@pxeger I don't know if it is a valid random source, but it seems that it choose evenly a number on the wanted interval at each execution. As I saw the same trick on other problems using random, I thought I could use it here. Otherwise I have also my first solution :p

Zsh, 37 bytes
<<<\#`tr -dc 0-9a-f</*/ur*m|head -c6`

Try it online!

</*/ur*m: input from /dev/urandom (shortened with wildcards)
tr -dc 0-9a-f: keep only characters in the range 0-9a-f
head -c6: take the first 6 characters
<<<#``: prepend # and print

Vyxal Ṫ, 7 bytes
\#6(k6℅

Try it Online!
Explanation
\#6(k6℅
\#      Push "#"
   (    For _
  6     in range(6):
    k6    "0123456789abcdef"
      ℅   Random item

Ṫ Concatenate the stack

Python 3, 32 bytes
print(f"{hash('a'):x}#"[:-8:-1])

Bash (51)
od -N4 -An -tx /dev/urandom | cut -c2-7 | sed s/^/#/

Python 3, 53 bytes
from random import*;print(f"#{randint(0,16**6):06x}")

Try it online!

Python 3, 50 bytes
import time
print(f"#{int(time.time()%16**6):6x}")

Try it online!
Random generation by modulo of current time saves two precious bytes
Also 0 before 06x can be omitted

using f"{i:6x} will give leading spaces instead of 0 when i is less than 6 digits long in hexadecimal. You should instead use the format f"{i:06x}. But you also can gain 1 byte by replacing 16**6 by 8**8 an 2 bytes using "%06x"%i instead using the previous f-string syntax : Try it online!

Nim, 57 bytes
import colors,random
randomize()
echo 0xffffff.rand.Color

Try it online!

Jelly, 9 bytes
6ØhX¤€”#;

Try it online!
Explanation
6ØhX¤€”#;   Main niladic link
6           6
     €      Map
    ¤       (
 Øh           "0123456789abcdef"
   X          Choose random
    ¤       )
        ;   Prepend
      ”#      "#"

Julia 1.0, 24 bytes
'#'repr(rand(UInt))[3:8]

Try it online!

Japt -P, 11 bytes
Gö6 msG i'#

Test it

Ly, 29 26 bytes
'#o6['0'??'9G[p'(+,0]po,]p

Try it online!
At a high level, here's how this one works...

write out #
loop 6 times...
each iteration, write out a random digit in 0-f range

And for people who like gory details about stacks. :)
'#o6['0'??'9G[p'(+,0]po,]p
'#o                        - push "#" on stack, print it as char
   6[                  ,]  - loop 6 times
     '0'?                  - push "0" and "?" codepoints on stack
         ?                 - pick a random number between them
          '9G              - is it greater then "9" codepoint?
             [p    0]p     - if/then, called if pick is > "9"
               '(          - push 28 on stack (Note 1)
                 +         - add 28 to random pick (Note 1)
                  ,        - decrement (Note 1)
                      o    - print top of stack as a char
                         p - clear the loop artifact from the stack

Note 1: Mapping the codepoints :-? to a-f means adding 27 to the codepoint.  The shortest way to do that would be to push ' onto the stack, but the code for that (at least on TIO) '' doesn't work.  So this code loads 28 (which is ( then decrements the result with , instead.

Java (JDK), 54 bytes
n->"#"+Long.toHexString((int)(Math.random()*0xffffff))

Try it online!

C (tcc), 46 43 bytes
-3 bytes, thanks @ceilingcat
main(){srand(main);printf("#%08X",rand());}

Try it online!
4 byte color codes are valid, the last byte is used as alpha.
C is weird with random numbers because of how old it is. While the code above is technically a valid answer, it does a really bad job because different compilers treat rand() differently and often use a suboptimal generator, in addition to not actually guaranteeing every possible color. Importing a better library for generation isn't exactly a good idea for Code Golf though.

42 bytes

Mathematica, 30 bytes
0xfff == 4095, so we can just take a random integer from 0-4095 and convert it to hexadecimal form. We save a few characters using prefix and infix notation.
RandomInteger@4095~BaseForm~16

Try it online!

Zsh (coreutils), 26 bytes
Using jot, originally in BSD Unix. Try it Online.
jot -w\#%x -r 1 0 16777216

Red, 18 bytes
random 255.255.255

I don't think it gives the number in hexadecimal or adds # to the front.

Welcome to the site.  Can you provide some way to test this?  As Bubbler pointed out it looks like it doesn't work.

Python 3.8 (pre-release), 43 bytes
from os import*
print("#"+urandom(3).hex())

Try it online!
1 byte less than current top Python 3 sol by @Jakque, as I don't think that one by @Ivar Matstoms is fair

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


text:
Shortest program whose concatenated program+output is a permutation of the 95 printable ASCII characters
Write a program that's as short as possible (as measured by byte-count), takes no input, contains no comments, and outputs a character string/sequence, such that concatenated program+output is exactly 95 characters long and contains every printable ASCII character exactly once, i.e. program+output is a permutation of the 95 characters with ASCII codes 32-126:
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

In the event of a tie, the winner is the entry whose (95-character) concatenated program+output is closest to the above string, as measured by the Levenshtein edit-distance (i.e. the number of single-character deletions, insertions, or substitutions required to put it into ASCII order).

You may want to restrict the trivial cat submission.

So does this mean that if e.g. the program contains any repeated characters it is automatically disqualified? That's rough.

Related: http://codegolf.stackexchange.com/questions/12368/print-every-character-your-program-doesnt-have/12373#12373

As soon as I find  out how to discharge all of #, " and ' in any language, I'll be sure to write an answer. I think I can discharge them in Ruby.

You might also want to rule on whether the old echo $0 is disqualified.

Are characters outside of the printable ascii character range (and possibly duplicates thereof) allowed? Or must the program+output contain every printable character exactly once, and nothing more?

@primo I assume they are allowed. I think it's time to write a "shift-and-eval" solution that uses duplicates (though string literals are going to be hard to get)

GolfScript, 14 characters
{`),32>46-^}.~

Output:
 !"#$%&'(*+/015789:;<=?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]_abcdefghijklmnopqrstuvwxyz|

The challenge (at least as far as I understand it) was to write a program whose program and output is a permutation of the 95 printable ASCII chars, not to write the shortest possible program that outputs the 95 printable ASCII chars.

Sorry, my mistake. In the title it reads "program+output", whereas later in the question it reads concatenated program+output.

), - wow. I love that.

@JanDvorak codegolf.SE: the only place where people get excited about a close-paren and a comma. :P

@Doorknob in golfscript it means "right uncons (rparen) and make an array of that size (comma)". In effect you're left with a string shortened by one character (the right curly) and an array ending just below that character's ASCII position (at |). Trim the unprintable chars, the period and xor (symmetric set difference here) with the source code (subtraction is taken) sans said right curly, and you're done. And yeah, string xor array is string.

Perl, 89 characters
This is the best I've been able to do so far:
q< !"#%&'()+/8:?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\^_`abcdefghjklmosuvwxz|>;
print~-$=.73*2,y[]{}

For those not conversant in Perl minutae, the two arguments to the print statement could be rendered as ~(-($=)) . (73 * 2) and tr///.
The program outputs 6 characters:
591460

Unfortunately every single iteration construct that I can think of in Perl (for, while, until, map, grep) shares at least one character with print. If newlines were allowed to appear in the output, then I could use Perl 5.010 to eke out an 87-character solution:
q{ !"#%&'*,-./0:;>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^`bcdfgjkmnoprtuvxz|~}while($_+=say)<9

Let's see if I can print a bigger number :-)

uh... can you translate the second line for me?

@JanDvorak $= is the number of horizontal lines in the current output device. By default 60. ~-$= is the bitwise inversion of the two's complement negative of 60, which happens to be 59. 73*2 is 146. . and , do what you would expect of them. y[]{} is another way to say tr///, which is the transliterate operator. It takes $_ and does nothing, because you didn't give it any characters to replace. It returns the number of characters replaced, which is 0. So we have ~-$= . 73*2 , y[]{} = 59 . 146 , 0 = '591460`.

PHP 67 bytes
<?=U4eB1gkFdA6J9snZD2IE8y5PhwQV^xHGmqYMfNjKpbR3vcLalCWi0_TtrOSXouz;

Output:
-|"/@>& *+}:[!],'~(){.\`7#%$

It seems like there should be a 65 byte solution, outputting 30 chars instead of only 28, but I couldn't get it to line up. The 6 unused characters OSXouz have been tacked onto one of the string literals instead.
Edit: Upon further reflection, it is not possible to generate more than 28 characters in this manner. UPPER ^ lower will always result in a character between 32 and 63, so all 10 digits are required for @[\]_`{|}~. Four of the remaining 22 are used in the script itself, leaving only 18 which can be obtained with letters alone. The tiebreaker could be improved significantly, though.

Ah, sure, barewords. How could I have forgot?

Ruby, 91 chars
%{ !"#$&\',-/450:<=>ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcefghijklmnqvwxyz|~};puts(?@.ord*98+1)

Outputs 6273.
%{...} trick stolen from Jan Dvorak

Without comments. As clearly stated.

@JohannesKuhn Ah, didn't notice that. edited.

%{ !"#$&\',-/450:<=>ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\abcefghijklmnqvwxyz|~};puts(?@.ord*98+1)` is what I think you want (for 91 characters) with the semicolon moved over to be used as a printable separator (instead of a newline), and with the letters of 'ord' removed from inside the curly brackets.

@r.e.s. Yep, it's hard to manage all these letters :P

Now \ is included three times.

@Howard Fixed again :P

@Howard There are some extra ''s (intended as escape characters) that show up in my comment because of my failed attempt to format the string to display properly. Formatting comments -- as opposed to questions & answers -- can be a pain.

Perl, 61 characters
print$:x8^CJIBQTOWAEULHVGFNMKRPZY,q<#"/;*g~?|={.>&+u15m97ws26

Output:
c@db[yo]le_ah\jfD`kX}zS-! %)('v304

$: defaults to " \n-". x8 repeats it eight times; the 24-character result is then bitwise-xored with a 23-character barestring (the last - is left as-is). Second part is a 12-character q-string bitwise-and a 10-character barestring (the last 2 characters are discarded).

I find your program length is 61 characters.

Thanks. My text editor reported 62 characters because of the EOF.

Ruby, 95 characters, 6 edits
%{ !"#$&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz|~}

Yep. That's it. Just a free-floating string literal that is never printed. Ruby supports string literals (borrowed from Perl, I think) in the percent-type-delimiter form - the delimiter is any non-alphanumeric character, and if the opening delimiter is an opening bracket (any of [({<), the closing delimiter is the corresponding closing bracket (nested brackets are allowed).
I realise this is more of a baseline submission, but unless someone manages to actually print something or unless there's a language with a two-char freeform string literal with a different opening and closing delimiter, this is the best there is.

Tcl 96, edit distance 12
if 0    {!"#$%&'()*+,-./123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdeghjklmnopqrstuvwxyz|~}

One of the spaces should be a tab, I'm afraid

is a tab or space printable?

tab is unprintable (ASCII 9), but space is printable (ASCII 32).

I don't waste ink for a space.

Space is the only printable character that you print by not printing. You can print a tab by not printing as well, but while space is printable, tab is unprintable.

Anyway. it's a tab now.

I don't think tabs are allowed: (quoting from rules) "program+output is exactly 95 characters long and contains every printable ASCII character exactly once"

[Just saw that the OP only clarified this after you answered :)]

I hate chameleon questions. I was going to use unicode characters for an other solution.

join {!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_\abcdefghklmpqrstuvwxyz|~}` seems to work using 95 characters? (Thank you for your entry. Sorry about the chameleon -- unfortunately I edited in haste, and should have done things differently.)

yeah, but I like the if 0. list would be probably better (it takes a string, not a list).


text:
Program which tells two different storys
this code looks like a story but does nothing useful. My challenge for you guys is to write piece of code which sounds like another story but it must generate output - another story.
So the point of challenge to make valid code which can be read like a logical story/poem/tale, also it must generate output - another story/poem/tale.
It is not real code golf, so you can produce as much code as you need, also there is no need generate very long output with small piece of code, everything is about ingenuity. However there is only one limit in code, output needs to be longer then Why did the chicken cross the road?
My own opinion is not objective so the winner will be the top answer by votes. Will not accept an answer until 1st of November.

The help pages state "All questions on this site [...] should have an objective primary winning criterion".

Really cool idea though. :)

answer_valid = false if !english_grammar_check(output)  ?

if you drop the choose one of the 3 most highest voted answers, it could be [tag:popularity-contest]

Why is there a 'popularity-contest' -tag, if an objective winning criterion is a must for any question?

@shiona "Highest voted answer at x time" is objective.