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

Answer by DavidC for Implement division using only addition

$
0
0

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


Viewing all articles
Browse latest Browse all 18

Trending Articles



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