가감 승제 의 c + + 실현

1810 단어 C/C++
알고리즘 설명 참조:http://www.cnblogs.com/kiven-code/archive/2012/09/15/2686922.html
#include 
using namespace std;

int Add(int a,int b)//  
{
	int x,y,icarry=0;//icarry    
	int result=0;

	//          
	for(int n=0;n<32;n++){
		// a,b   
		x=a&1;
		y=b&1;
		
		//           
		int bit=0;
		bit=(x^y)^icarry;
		icarry=(x&y)|(y&icarry)|(icarry&x);
		if(bit==1)
			result=result|(1<>1;
		b=b>>1;
	}
	return result;
}
int Sub(int a,int b)//  
{
	b=Add(~b,1);//  
	return Add(a,b);
	//   :
	/*	return Add(a,-b);*/
}
int mul(int a,int b)//  
{
	int sign=a^b;//sign<0      
	int result=0;//    
	//a,b   
	a=a<0?Add(~a,1):a;
	b=b<0?Add(~b,1):b;
	
	while(a)
	{
		if(a&0x1)
			result=Add(result,b);
		b=b<<1;
		a=a>>1;
	}
	if(sign<0) result=Add(~result,1);//     
	return result;
}
int divide(int a, int b)//  
{
	//           
	int dividend = a < 0 ? Add(~a, 1) : a;
	  int divisor = b < 0 ? Add(~b, 1) : b;

		//             
		int remainder = dividend;
		  int quotient = 0;

			while(remainder >= divisor)
			  {
					remainder = Sub(remainder, divisor);
						quotient = Add(quotient, 1);
			  }

			  //     
			  if((a ^ b) < 0)
				{
					  quotient = Add(~quotient, 1);
				}

			return quotient;
}

int remainder(int a, int b)//  
{
	//           
	int dividend = a < 0 ? Add(~a, 1) : a;
	  int divisor = b < 0 ? Add(~b, 1) : b;

		//             
		int remainder = dividend;
		  int quotient = 0;

			while(remainder >= divisor)
			{
					remainder = Sub(remainder, divisor);
						quotient = Add(quotient, 1);
			}

			  //     
			  if(a < 0)
				{
					  remainder = Add(~remainder, 1);
				}

				return remainder;
}
int main()
{
	int a=666666,b=-333333;
	cout<

좋은 웹페이지 즐겨찾기