fbpx

C++: Rational Number Arithmetic

Bjarne-stroustrup
 

The objective of this task is to create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.

For example: Define a new type called frac with binary operator “//” of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).

Further define the appropriate rational unary operators abs and ‘-‘, with the binary operators for addition ‘+’, subtraction ‘-‘, multiplication ‘×’, division ‘/’, integer division ‘÷’, modulo division, the comparison operators (e.g. ‘<‘, ‘≤’, ‘>’, & ‘≥’) and equality operators (e.g. ‘=’ & ‘≠’).

Define standard coercion operators for casting int to frac etc.

If space allows, define standard increment and decrement operators (e.g. ‘+:=’ & ‘-:=’ etc.).

Finally test the operators: Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.

#include <iostream>
#include "math.h"
#include "boost/rational.hpp"

typedef  boost::rational<int> frac;

bool is_perfect(int c)
{
	frac sum(1, c);
	for (int f = 2;f < sqrt(static_cast<float>(c)); ++f){

		if (c % f == 0) sum += frac(1,f) + frac(1, c/f);
	}
	if (sum.denominator() == 1){
		return (sum == 1);
	}
	return false;
}

int main()
{
	for (int candidate = 2; candidate < 0x80000; ++candidate){
		if (is_perfect(candidate)) 
		std::cout << candidate << " is perfect" << std::endl;
	}
	return 0;
}

SOURCE

Content is available under GNU Free Documentation License 1.2.