Problem 67

Back to Problem Solutions forum

james_cranston     2014-08-27 15:16:44

I want to know how can we deal with extremely large numbers with large digits in C.Such as 482606912159782542906419752914300739614957797444852212905387537805131416261365029062212271019541420375173999759675045 as we can't store it in any data type exactly as it is.

Guy Gervais     2014-08-27 15:45:22
User avatar

If you don't want to write your own BigNumber library (a good bet), you can use the GMP library.

james_cranston     2014-08-27 15:49:17

I am using code blocks on windows , how can I use GMP?

Guy Gervais     2014-08-27 16:11:49
User avatar

Sorry, I'm not familiar with Code Blocks (I know the name, but never used it). Googling for "code blocks gmp" should give you some help, although most people seem to be using it on Linux.

Alternatively, you could do the problems that require "Big Integer" support using a higher level language that has them built-in (Java, Python, C#, Ruby... pretty much anything other than C/C++). if you prefer to stay with compiled languages, D has Big Integer support in its base library.

Rodion (admin)     2014-08-27 16:28:44
User avatar

Hi!

Really this problem does not require writing complete long arithmetics library.

You only need to implement addition of the long values. This could be easily done in C if you represent each value as an array of chars (one digit per cell). It is convenient to store digits in reverse order by the way.

Addition itself should be implemented just as we calculate with pencil and paper - loop through digits starting from the end and add corresponding ones, if the result is greater than 9 remember it and add 1 to the next digit.

Something like this for summing 314 and 159:

char[10] a = {4, 1, 3};
char[10] b = {9, 5, 1};
char carry = 0;
for (i = 0; i < 10; i++) {
    a[i] += b[i] + carry;
    if (a[i] > 9) {
        a[i] -= 10;
        carry = 1;
    } else {
        carry = 0;
    }
}

Other option is to use any language supporting long arithmetics out-of-the-box (though of course it is good to try and implement it yourself at least once).

A Chauhan     2016-03-03 19:36:24
User avatar

Hello, Admin! Thanks for giving me the direction!

Please login and solve 5 problems to be able to post at forum