Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing big numbers (nearly 100.000 digits) in C++

Tags:

c++

How to store a huge number of nearly 100000 digits in C++?..

I have tried using long long int and long double int..Nothing worked for me..

Is there any other way to store such a huge number?

I wish to find the smallest palindrome larger than the given huge number.

like image 944
Sivakumar K R Avatar asked Dec 26 '22 18:12

Sivakumar K R


1 Answers

Upon further clarification in the comments section:

Yes, you can represent your number as a std::string in C++.

Here you find code for incrementing a number represented as a string:

#include <string>
#include <iostream>
#include <ostream>

void increment_numerical_string(std::string& s)
{
    std::string::reverse_iterator iter = s.rbegin(), end = s.rend();
    int carry = 1;
    while (carry && iter != end)
    {
        int value = (*iter - '0') + carry;
        carry = (value / 10);
        *iter = '0' + (value % 10);
        ++iter;
    }
    if (carry)
        s.insert(0, "1");
}

int main()
{
    std::string big_number = "123456789012345678901234567899";
    std::cout << "before increment: " << big_number << "\n";
    increment_numerical_string(big_number);
    std::cout << "after increment:  " << big_number << "\n";
}

You can use this in a loop to increment your big number and check if the resulting string is a palindrome:

if( equal(s.begin(), s.begin() + s.size()/2, s.rbegin()) )
    std::cout << "is a palindrome.\n";
else
    std::cout << "is NOT a palindrome.\n";

Edit

I do not claim this to be an efficient and correct solution to the problem. It's just a representation and incrementing method for big numbers.

like image 117
nurettin Avatar answered Jan 08 '23 11:01

nurettin