Typically, to handle integers that exceed the range of long long in C++, you'd have to represent them as string and perform operations on them that way. But, I found this code on the internet which seems to work like magic. It calculates any sum of powers of two (without 2^0), even though it can't be stored in a long long.
#include <iostream>
#include <cmath>
#include <iomanip>
#include <sstream>
using namespace std;
int main() {
int n;
stringstream ss;
cin >> n;
ss << fixed << setprecision(0) << pow(2, n + 1) - 2;
if (n >= 54) {
string a = ss.str();
a[a.size() - 1] = ((a[a.size() - 1] - 48) - 2) + 48;
cout << a;
return 0;
}
cout << ss.str();
}
How does it work? Will it work for any operation involving large numbers? If the value of n is very big (I tried 1024) it just prints "inf". What's the upper-limit of the range of numbers that can be calculated this way?
What exactly does the following part do and why does it do it?
a[a.size() - 1] = ((a[a.size() - 1] - 48) - 2) + 48;