Hi,

Is there any way to store huge numbers (for example, a number with a million digits) in a C program and be able to perform operations on it ?

Thanks..

Dani AI

Generated

raised the core question (million-digit integers). As pointed out, a hand-rolled string-based implementation is possible for learning purposes; as noted, production work at that scale is best done with a battle-tested arbitrary-precision library. Libraries manage limb-based storage, avoid O(n^2) traps, and switch to fast multiplication algorithms (Karatsuba, Toom-Cook, Schonhage-Strassen) when needed. See the GMP manual and the Boost.Multiprecision cpp_int docs for concrete APIs.

A minimal C++ example using Boost.Multiprecision (convenient, header-only) shows usage patterns:

#include <boost/multiprecision/cpp_int.hpp>
#include <iostream>
#include <string>

using boost::multiprecision::cpp_int;

int main() {
    std::string s = /* load million-digit decimal string */;
    cpp_int n = 0;
    for (char c : s) n = n * 10 + (c - '0'); // simple conversion
    cpp_int r = n * n; // example operation
    std::cout << r << '\n';
    return 0;
}

Practical notes: a million decimal digits in text is ~1 MB; in binary it is about 3.322e6 bits (~0.4 MB). Naive O(n^2) multiplication on such sizes is impractical—use libraries that provide FFT-based multiplication. For best throughput, prefer GMP for heavy work (and its mpz_import for fast binary imports), parse/print in large chunks, and test/profile on smaller scales before scaling up.

Recommended Answers

All 4 Replies

using std::string and operator overloading, yes it is able

Hi, thanks for your reply..

Can you elaborate the procedure.. It would be very helpful if you could post a link with the mentioned approach...

Thanks :)

There are tons of freeware libraries to perform ops over arbitrary precision numbers in C and C++. Search Google for "C arbitrary precision numbers library". For example:

It's not so easy to invent a new library in this area...

string num1 = "1234";
string num2 = "4567";
string sum = "";
char tmp2 = 0;
1. reverse num1 and num2
2. for 0 to string size() do 
char tmp = num1[i] + num2[i] + tmp2;
tmp2 = 0;
if (tmp > '9'){
  tmp-=10;
  tmp2 = 1;
}
sum+=tmp;

3. reverse sum and that's it :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.