ISourceCode

Make the frequent cases fast and the rare case correct

Algorithm to implement *, – , / operations using only ‘+’ operator

This is a simple algorithm of implementing methods that we learned in school.
Considered integers and not float.

Subtract :
(a-b) = a + (-1)*b
Product :
Multiply a by b by adding a ‘b’ no of times
Quotient :
subtract b from a until reaching 0. count the number of times you did this.
NOTE: only quotient is returned not the remainder

import java.io.*;
import java.lang.*;

public class Arithmetic 
{
	public static int Negating(int a) 
	{
	   	int neg = 0;
	   	int d = a < 0 ? 1 : -1;
	   	while (a != 0) 
	   	{
		      neg += d;
		      a += d;
	   	}
    	   	return neg;
	}
        // Check if a and b are different signs 
	public static boolean CheckSign(int a, int b) 
	{
		return ((a < 0 && b > 0) || (a > 0 && b < 0)) ? true : false;
	}
        // Return absolute value 
	public static int absolute(int a) 
	{
		if (a < 0) return Negating(a);
		else return a;
	}
	// Subtract two numbers by negating b and adding them 
	public static int Difference(int a, int b) 
	{	
		return a + Negating(b);
	}
	// Multiply a by b by adding a 'b' no of times 
	public static int Product(int a, int b) 
	{
		if (a < b) return Product(b, a); // algo is faster if b < a
	   	int sum = 0;
	   	for (int i = absolute(b); i > 0; --i) sum += a;
	   	if (b < 0) sum = Negating(sum);
	   	return sum;
	}
	// subtract b from a until reaching 0. count the number of times you did this 
	public static int Quotient(int a, int b) throws java.lang.ArithmeticException 
	{
		if (b == 0) 
		{
			throw new java.lang.ArithmeticException("Divide by 0.");
	   	}
	   	int quotient = 0;
	   	int divisor = Negating(absolute(b));
	   	int divend; 
	   	for (divend = absolute(a); divend >= absolute(divisor); divend += divisor) 
		{
		      ++quotient;
	   	}
	   	if (CheckSign(a, b)) quotient = Negating(quotient);
	   	return quotient;
	}
	public static void main(String args[]) throws IOException
	{
		int a=8,b=-4;
		System.out.println(" The Difference of the two numbers is " +Difference(a,b)); 
		System.out.println(" The Product of the two numbers is " +Product(a,b));
		System.out.println(" The Quotient of the two numbers is " +Quotient(a,b));       
	}
}

OUTPUT:

laptop:~/code$ java Arithmetic
The Difference of the two numbers is 12
The Product of the two numbers is -32
The Quotient of the two numbers is -2

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: