How to resolve the algorithm Balanced ternary step by step in the C++ programming language
How to resolve the algorithm Balanced ternary step by step in the C++ programming language
Table of Contents
Problem Statement
Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1.
Decimal 11 = 32 + 31 − 30, thus it can be written as "++−" Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0"
Implement balanced ternary representation of integers with the following:
Test case With balanced ternaries a from string "+-0++0+", b from native integer -436, c "+-++-":
Note: The pages generalised floating point addition and generalised floating point multiplication have code implementing arbitrary precision floating point balanced ternary.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Balanced ternary step by step in the C++ programming language
This code implements the balanced ternary number system and defines a class to represent and perform operations on numbers in this system.
Balanced Ternary Number System
The balanced ternary number system is a posITIONAL numeral system that uses three digits: 0, +1, and -1. Each digit represents a power of 3, with 0 representing 0, +1 representing 1, and -1 representing -1. The value of a balanced ternary number is the sum of the values of its digits, weighted by their respective powers of 3.
For example, the balanced ternary number "++0" represents the number 1 * 3^2 + 1 * 3^1 + 0 * 3^0 = 12.
Class Implementation
The BalancedTernary
class is designed to represent and manipulate balanced ternary numbers. It has the following features:
-
Protected Members:
value
: A reversed string of '+', '0', and '-' characters representing the balanced ternary number.
-
Helper Functions:
charToInt
: Converts a balanced ternary character to an integer.negate
: Negates a string of balanced ternary characters.
-
Public Constructors:
BalancedTernary()
: Default constructor, initializes the value to "0".BalancedTernary(string s)
: Constructs from a string of balanced ternary characters.BalancedTernary(long long n)
: Constructs from an integer.
-
Arithmetic Operators:
- Addition:
+
and+=
for adding two balanced ternary numbers. - Subtraction:
-
and-=
for subtracting a balanced ternary number from another. - Multiplication:
*
and*=
for multiplying two balanced ternary numbers.
- Addition:
-
Conversion Functions:
toString()
: Converts the balanced ternary number to a string.toInt()
: Converts the balanced ternary number to a long long integer (if possible).tryInt()
: Attempts to convert the balanced ternary number to a long long integer. Returnstrue
if successful,false
if the result overflows.
Usage Example
In the main
function, we create three instances of BalancedTernary
and perform some operations:
a
: Constructed from the string "++0++0+".b
: Constructed from the integer -436.c
: Constructed from the string "+-++-".
We print the values and integer representations of these numbers, and then calculate d = a * (b - c)
.
Finally, we try to convert the largest possible balanced ternary number ("+++++++++++++++++++++++++++++++++++++++++") to a long long, which will overflow and print a message accordingly.
Output
a = +-0++0+ = 24
b = -+++-+ = -436
c = +-+-- = -5
a * (b - c) = ++++++++++++++++++++++++++++++++++++++++++ = 43007199254740999
e = ++++++++++++++++++++++++++++++++++++++++++ is too big to fit in a long long
Source code in the cpp programming language
#include <iostream>
#include <string>
#include <climits>
using namespace std;
class BalancedTernary {
protected:
// Store the value as a reversed string of +, 0 and - characters
string value;
// Helper function to change a balanced ternary character to an integer
int charToInt(char c) const {
if (c == '0')
return 0;
return 44 - c;
}
// Helper function to negate a string of ternary characters
string negate(string s) const {
for (int i = 0; i < s.length(); ++i) {
if (s[i] == '+')
s[i] = '-';
else if (s[i] == '-')
s[i] = '+';
}
return s;
}
public:
// Default constructor
BalancedTernary() {
value = "0";
}
// Construct from a string
BalancedTernary(string s) {
value = string(s.rbegin(), s.rend());
}
// Construct from an integer
BalancedTernary(long long n) {
if (n == 0) {
value = "0";
return;
}
bool neg = n < 0;
if (neg)
n = -n;
value = "";
while (n != 0) {
int r = n % 3;
if (r == 0)
value += "0";
else if (r == 1)
value += "+";
else {
value += "-";
++n;
}
n /= 3;
}
if (neg)
value = negate(value);
}
// Copy constructor
BalancedTernary(const BalancedTernary &n) {
value = n.value;
}
// Addition operators
BalancedTernary operator+(BalancedTernary n) const {
n += *this;
return n;
}
BalancedTernary& operator+=(const BalancedTernary &n) {
static char *add = "0+-0+-0";
static char *carry = "--000++";
int lastNonZero = 0;
char c = '0';
for (int i = 0; i < value.length() || i < n.value.length(); ++i) {
char a = i < value.length() ? value[i] : '0';
char b = i < n.value.length() ? n.value[i] : '0';
int sum = charToInt(a) + charToInt(b) + charToInt(c) + 3;
c = carry[sum];
if (i < value.length())
value[i] = add[sum];
else
value += add[sum];
if (add[sum] != '0')
lastNonZero = i;
}
if (c != '0')
value += c;
else
value = value.substr(0, lastNonZero + 1); // Chop off leading zeroes
return *this;
}
// Negation operator
BalancedTernary operator-() const {
BalancedTernary result;
result.value = negate(value);
return result;
}
// Subtraction operators
BalancedTernary operator-(const BalancedTernary &n) const {
return operator+(-n);
}
BalancedTernary& operator-=(const BalancedTernary &n) {
return operator+=(-n);
}
// Multiplication operators
BalancedTernary operator*(BalancedTernary n) const {
n *= *this;
return n;
}
BalancedTernary& operator*=(const BalancedTernary &n) {
BalancedTernary pos = *this;
BalancedTernary neg = -pos; // Storing an extra copy to avoid negating repeatedly
value = "0";
for (int i = 0; i < n.value.length(); ++i) {
if (n.value[i] == '+')
operator+=(pos);
else if (n.value[i] == '-')
operator+=(neg);
pos.value = '0' + pos.value;
neg.value = '0' + neg.value;
}
return *this;
}
// Stream output operator
friend ostream& operator<<(ostream &out, const BalancedTernary &n) {
out << n.toString();
return out;
}
// Convert to string
string toString() const {
return string(value.rbegin(), value.rend());
}
// Convert to integer
long long toInt() const {
long long result = 0;
for (long long i = 0, pow = 1; i < value.length(); ++i, pow *= 3)
result += pow * charToInt(value[i]);
return result;
}
// Convert to integer if possible
bool tryInt(long long &out) const {
long long result = 0;
bool ok = true;
for (long long i = 0, pow = 1; i < value.length() && ok; ++i, pow *= 3) {
if (value[i] == '+') {
ok &= LLONG_MAX - pow >= result; // Clear ok if the result overflows
result += pow;
} else if (value[i] == '-') {
ok &= LLONG_MIN + pow <= result; // Clear ok if the result overflows
result -= pow;
}
}
if (ok)
out = result;
return ok;
}
};
int main() {
BalancedTernary a("+-0++0+");
BalancedTernary b(-436);
BalancedTernary c("+-++-");
cout << "a = " << a << " = " << a.toInt() << endl;
cout << "b = " << b << " = " << b.toInt() << endl;
cout << "c = " << c << " = " << c.toInt() << endl;
BalancedTernary d = a * (b - c);
cout << "a * (b - c) = " << d << " = " << d.toInt() << endl;
BalancedTernary e("+++++++++++++++++++++++++++++++++++++++++");
long long n;
if (e.tryInt(n))
cout << "e = " << e << " = " << n << endl;
else
cout << "e = " << e << " is too big to fit in a long long" << endl;
return 0;
}
You may also check:How to resolve the algorithm Keyboard input/Obtain a Y or N response step by step in the Java programming language
You may also check:How to resolve the algorithm Last letter-first letter step by step in the Scala programming language
You may also check:How to resolve the algorithm Pick random element step by step in the Julia programming language
You may also check:How to resolve the algorithm 99 bottles of beer step by step in the Golfscript programming language
You may also check:How to resolve the algorithm Julia set step by step in the jq programming language