1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int Age, Base;
//======================================================================
int result( int a, int b, int &carry ) // Special alien arithmetic: 1 digit
{ // Inductively, carry is either -1, 0 or 1
int sum = a + b + carry; // Unbounded sum; lies between -Base and +Base
carry = ( sum + Age ) / Base + ( sum - Age ) / Base;
return sum - Base * carry;
}
//======================================================================
int main()
{
Age = 3;
Base = Age + 1 + Age;
const int Ndigits = 6;
string leftover[] = { "-1", " ", " 1" }; // Any carry-over left at end; needs possible blank
int a[Ndigits], b[Ndigits], c[Ndigits];
cout << "Enter the alien's first 6 digits, separated by spaces: ";
cin >> a[5] >> a[4] >> a[3] >> a[2] >> a[1] >> a[0];
cout << "Enter the alien's second 6 digits, separated by spaces: ";
cin >> b[5] >> b[4] >> b[3] >> b[2] >> b[1] >> b[0];
int carry = 0;
c[0] = result( a[0], b[0], carry ); // Looks horrible without loops!
c[1] = result( a[1], b[1], carry );
c[2] = result( a[2], b[2], carry );
c[3] = result( a[3], b[3], carry );
c[4] = result( a[4], b[4], carry );
c[5] = result( a[5], b[5], carry );
#define SP << setw( 3 ) <<
cout << " " SP a[5] SP a[4] SP a[3] SP a[2] SP a[1] SP a[0] << '\n';
cout << " " SP b[5] SP b[4] SP b[3] SP b[2] SP b[1] SP b[0] << '\n';
cout << string( 21, '-' ) << '\n';
cout << leftover[carry+1] SP c[5] SP c[4] SP c[3] SP c[2] SP c[1] SP c[0] << '\n';
}
|