Click here to Skip to main content
15,896,153 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
C++
Mint Mint::operator+=(const Mint &rhs) {
	int sum;
	int carry = 0;
	unsigned int i;
	unsigned int len = num.size();
	if (len < rhs.num.size())
	{
		len = rhs.num.size();
	}
	for (i=0;i<len;i++)
	{
		sum = num[i] + rhs.num[i] + carry;
		carry = sum / 10;
		sum = sum % 10;
		if (i < len)
		{
			num[i] = sum;
		}
		else
		{
			num.push_back(sum);
		}

	}
	if(carry != 0 )
	{
		num.push_back(carry);
	}
	return *this;
}


hello everyone
can you please check out this implementation of the += operator
i'm trying to write a class that deals with large integer numbers so i wrote this for the += operator and it works just fine for numbers that have the same size but when i try to add 2 numbers of different size i get some weird result

any advice
Posted

A simple method of 'normalisation' would be to take the shorter of the two numbers and make it the same as the longer one. Just expand it on the left with zeroes until they are both the same size. The addition should then work.
 
Share this answer
 
Comments
Member 12223678 31-Dec-15 9:56am    
than you for the answer but i'm not sure how would that work since i'm passing the rhs as const (const Mint &rhs)
Richard MacCutchan 31-Dec-15 10:06am    
You would need to copy it to a temporary location. You also need to take into account the situation when the LHS is the shorter number.
C++
Mint Mint::operator+=(const Mint &rhs) {
	int sum;
	int carry = 0;
	unsigned int i;

	if (num.size() < rhs.num.size())
	{
		while(num.size() < rhs.num.size())
		{
			num.push_back(0);
		}
	}
	unsigned int len = num.size() ;

	for (i=0;i<len;i++)>
	{
		sum = num[i] + rhs.num[i] + carry;
		carry = sum / 10;
		sum = sum % 10;
		if (i < len)
		{
			num[i] = sum;
		}
		else
		{
			num.push_back(sum);
		}

	}
	if(carry != 0 )
	{
		num.push_back(carry);
	}
	return *this;
}

would something like this work.?
 
Share this answer
 
Comments
Richard MacCutchan 31-Dec-15 11:04am    
What happens when you try it?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900