let's implement the simple div method using subtraction. - Java java.lang

Java examples for java.lang:int

Description

let's implement the simple div method using subtraction.

Demo Code


//package com.java2s;

public class Main {
    /**// w  w  w.  jav a  2s. co m
     * let's implement the simple div method using subtraction.
     * Approach :Keep (dividend-divisor) until the remainder is less than divisor
               Performance is slow, e.g. 2000000/1 = O(n) where in is dividend.
     * @param divident
     * @param divisor
     * @return quotient without decimals.
     */
    public static int divisionSolution1(int divident, int divisor) {
        int quotient = 0;//return result
        int loopTime = 0;
        int neg = 1;
        //invalid data.
        if (divisor == 0) {
            throw new ArithmeticException("divisor is 0");
        }
        //invalid data.
        if (divisor == 1) {
            return 1;
        }
        if (divident == divisor)
            return 1;
        //One of the two are negative (dividend and divisor) not both at the same time
        if ((divident > 0 && divisor < 0) || (divident < 0 && divisor > 0)) {
            neg = -1;
        }
        // convert to positive
        divident = (divident < 0) ? -divident : divident;
        divisor = (divisor < 0) ? -divisor : divisor;

        while (divident >= divisor) {
            loopTime++;
            divident -= divisor;//while the remainder is larger than divisor, we keep subtracting
            quotient++;//do not forget update quotient!
        }
        System.out.println("Naive loop time: " + loopTime);
        return quotient * neg;
    }
}

Related Tutorials