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

Answer by Joop Eggen for Implement division using only addition

$
0
0

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);}

Viewing all articles
Browse latest Browse all 18

Trending Articles



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