Thursday, January 27, 2011

Dealing with Really big numbers.

Yesterday evening, I was trying to solve a problem which deals with multiplying really huge integers. As we know, in most of the programming languages integer data type has limit on the size of integer. Generally, it depends on the processor word size. In 32 bit machines, it would be 32 bits.
So, biggest unsigned integer that could be held in, is 4294967296, just 10 digits. What if we have to deal with 100 digit numbers???

Problem: Find the sum of natural numbers till N, N will be really huge, say 80 digits.

Obviously, we couldn't work with basic data type Integer. We can implement our own Abstract Data Type for this. Still, choosing perfect algorithm for processing is difficult.

There are some languages, which do support big integers naturally, like Haskell, Pike. Some languages like Java, supports big integers using different data type rather than usual Integer type. Haskell's limit for integer depends only on Main memory. Pike also supports integers of huge size.

I evaluated Pike yesterday. Certain characteristics of Pike are really interesting. Syntax in Pike is almost equivalent to C /C++. It is garbage collected and Object oriented language. I am just showing a Pike program for the above problem here.

int main()
{
string countStr; int count;
countStr = Stdio.stdin->gets();
sscanf(countStr, "%d", count);
while( count--)
{
int realInt;
string strInt;
strInt = Stdio.stdin->gets();
sscanf(strInt, "%d", realInt);
int res = realInt * (realInt + 1) / 2;
string outStr = sprintf("%d\n", res);
write(outStr);
}

return 0;

}

You could find there is no much difference in the syntax, if you are a C/ C++ programmer. It is very fast in handling really big integers. I tested and played with some other library functions in Pike. Hope you will also try and play with this innovative language.

In next blog, I will explain my experiences with Haskell.

Thanks for reading.

No comments:

Post a Comment