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 suma+b
and increments counter variablez
each time an addition is performed. If eithera
orb
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 variablesq
,u
, andv
. Maximum recursion depth is the number of bits ina
, and the recursion is linear rather than a tree. (Note: theb
in this function is the originalb
multiplied by a power of 2.)divide(a,b)
returns floor(a/b) as required.- Compiles with warnings (because code is golfed). Runs fine.