//subtraction is needed for division. Of course i can do cool subtraction via cool addition,but it's...inelegantint coolsub(int a,int b){ int c,result, tmp; c=((~a)&b)<<1; result=a^b; while(c!=0){ tmp=result^c; c=((~result)&c)<<1; result=tmp; }; return result;};const high_bit=( ~((unsigned int)(0)) ^ (~((unsigned int)(0))>>1) );int cooldivide(int a,int b){ if(b==0)return 0;//division by zero. What i should return.... if(b==1)return a; int s=0; //note that general >,<,<=,>= do subtraction :) if(a&high_bit){a=coolsub(0,a);s=1;} if(b&high_bit){b=coolsub(0,b);s^=1;} int c,d,m=1,r=0; c=b; d=c<<1; while(d>c){ c=d; d<<=1; m<<=1; } int e=a; int k=0; do{ k=coolsub(e,c); if((k&high_bit)==0){e=k;r+=m;}; m>>=1; c>>=1; }while((m!=0)&&(e!=0)); if(s){return coolsub(0,r);}else{return r;}}
and comparasion:
a<b
coolsub(a,b)&high_bit
a<=b
(coolsub(b,a)&high_bit)==0
> and >= is the same.
edit:as about subtraction via addition,
i'd rather do it in that way:
int coolsub2(int a,int b){
return cooladd(cooladd(~a,~b),2);
};
,rather than using coolmultiply to multiply with (~0) :).
And important thing, coolmultiply need simple fix to work with signed numbers, same as one used in cooldiv.
[Edited by - Dmytry on September 2, 2004 6:46:30 AM]