Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mathematical operations between two strings [duplicate]

I'm trying to add subtract and multiply numbers with huge decimals C++.

Example:

4125487821547.87879845215584844588 - 354556689.899455132265468

What I figured so far is that I need to save inputs as a string, but not sure how to proceed after that.

Appreciate the help in advance Thanks

like image 815
Djon Avatar asked Jan 02 '23 21:01

Djon


1 Answers

You need a big integer class or library. There are several implementations available, just to give you an overview on how to use such an external dependency, here is a solution based on Boost:

#include <boost/multiprecision/cpp_int.hpp>

using BigInt = boost::multiprecision::cpp_int;

You can now construct instances by passing string or integral literals to the constructor and do all standard arithmetic operations with these objects, e.g.

const BigInt i("8787984521558484092344588");
const BigInt j("32308942039402934");

std::cout << i - j << "\n";

One nice detail of such classes is that they usually demonstrate one of the few justified scenarios for non-explicit constructors with one argument, i.e., for the sake of smooth interoperability with builtin integral types. Example:

int n = 42;

// Use builtin ints like BigInts via implicit BigInt(int) ctor:
std::cout << (i + n)/(j % 3) << "\n";

You only need the Boost headers for these snippets, no linkage is required. Check out the docs when proceeding with this library.

like image 111
lubgr Avatar answered Jan 13 '23 18:01

lubgr