Ejemplo n.º 1
0
// Pre:
// 	1) a >= 0
// Constructively returns floor(a/2)
// Changes the remainder of a, possibly
Rational halfOf(Rational a) {
	if(a.getLength() == 1 && a.getDigit(0) == 0)
		return Rational ("0");
	string c = "";	
	stringstream ss;
	int curr = 0;
	int i = a.getLength()-1;
	int innerZeros = 0;
	while(i >= 0) {
		curr = 10*curr + a.getDigit(i);
		if(curr/2 > 0 || innerZeros) {
			innerZeros = 1;
			ss.str(string());
			ss << curr/2;
			c +=  ss.str();		
		}
		curr = curr%2;
		i--;
	}

	Rational d (c);
	if(a.getDigit(0)%2 == 1)
		d.setRemainder(1);
	return d;
}
Ejemplo n.º 2
0
// Pre:
// 	1) a >= b
// Constructively returns a-b
Rational subtract(Rational a, Rational b) {
	Rational c ("0");
	int i = 0;
	while(i < a.getLength()) {
		if(a.getDigit(i) >= b.getDigit(i))
			c.setDigit(i,a.getDigit(i)-b.getDigit(i));
		else {
			c.setDigit(i,a.getDigit(i)+10-b.getDigit(i));
			a.setDigit(i+1,a.getDigit(i+1)-1);
		}	
		i++;
	}	
	while(i > 1 && c.getDigit(i-1) == 0)
		i--;
	c.setLength(i);
	return c;
}
Ejemplo n.º 3
0
// Constructively returns a+b
Rational add(Rational a, Rational b) {
	int max = ((a.getLength() > b.getLength()) ? a.getLength() : b.getLength());
	int i = 0;
	Rational c ("0");
	c.setLength(max);
	while(i < max) {
		c.setDigit(i, c.getDigit(i) + a.getDigit(i) + b.getDigit(i));
		if(c.getDigit(i) > 9) {
			c.setDigit(i, c.getDigit(i)%10);
			c.setDigit(i+1, c.getDigit(i+1)+1);
			if(i == max-1)
				c.setLength(c.getLength()+1);
		}
		i++;
	}
	return c;
}