From the principle I had to solve the problem, it passed, I even whistled to second place :) very quickly.
We can accurately estimate the maximum size of a number, so we know what data array we need. I went on the way N*N
doubling, followed by subtraction 1. We need only two operations - doubling and subtracting 1. We take an array of 350 (with a margin) unsigned long
, and N*N
times we double it (we add the corresponding elements, if need to transfer). To quickly convert to decimal - in each element of the array, the values are limited to one billion. I keep track of the size of the number - so as not to summarize the extra ...
Of course, I can give the code here, but I'm not sure how good it is in the pedagogical sense :) I’ll show a little bit though.
class bigNum { public: bigNum() { a[0] = 1; } void mul2(); void dec() { a[0]--; } void out(); private: static const int size = 350; static const int lim = 1000000000; unsigned long a[size] = { 0 }; int last = 1; }; void bigNum::mul2() { unsigned long carry = 0; for(int i = 0; i < last; ++i) { a[i] *= 2; a[i] += carry; if (a[i] >= lim) { carry = a[i]/lim; a[i] %= lim; } else carry = 0; } if (carry) { a[last++] = carry; } };
PS To increase the speed, you can multiply, say, by 16 or 64 there, by changing the size accordingly ...