Quantcast
Channel: Implement division using only addition - Code Golf Stack Exchange
Viewing all articles
Browse latest Browse all 18

Answer by Todd Lehman for Implement division using only addition

$
0
0

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:

  1. 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.
  2. 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.)
  3. divide(a,b) returns floor(a/b) as required.
  4. Compiles with warnings (because code is golfed). Runs fine.

Viewing all articles
Browse latest Browse all 18

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>