views:

447

answers:

7

Can anyone please tell me how to multiply two number arrays in C? The number arrays are basically derived from two strings containing digits. eg: 123456 and 132465.

Edit: I had two string as S1 = "123456" and S2="132546". I then converted these two strings into array of ints i.e. int IS1[6] and IS2[6] so that

IS1[1] = 1, IS1[2] = 2......

and

IS2[1] = 1, IS2[2] = 3.....

Now I have to mulitply these two arrrays. Please help.

+4  A: 

It's not clear what exactly you want to multiply. If you need to multiply two null terminated strings in a char[], you can convert them to int values with atoi:

int result = atoi(str1) * atoi(str2);
Mehrdad Afshari
A: 

If your numbers are small enough, parse them into ints (atoi).

If they are too large to fit into ints:

  • use a library such as gmp

  • or use the pencil-and-paper algorithm, but you'll be reinventing the wheel.

Pascal Cuoq
+3  A: 

If you want to use the paper-and-pencil arithmetics and don't know how to do that, here is the illustration.

Michael Krelin - hacker
Nice link. Regarding the "pen-and-pencil", one of them has to be able to receive marks from the other.
Pascal Cuoq
Oops, Pascal, fixed this one. But it was funny.
Michael Krelin - hacker
A: 

Well, if you want to generate an array containing the multiplications, you could use:

int *a, *b, *c; // pointers to arrays of size n
for (unsigned i=0;i<n;++i)
  c[i] = a[i] * b[i];

If you want the inner product, this is how you could do it:

int *a, *b; // pointers to arrays of size n
int res = 0;
for (unsigned i=0;i<n;++i)
  res += a[i] * b[i];

If, like previous answers suggest, what you wanted was to treat the two arrays as numbers you could use the atoi() function as mentioned.

rmn
A: 

If it is for a real project, do the conversion.

If this is an exercise of algorithm, do the multiple loop according to the pencil and paper approach.

Dr. Xray
A: 

Search the web for "BigNum", "Big Integers". There are many packages that perform large number multiplication; some even have source code.

Thomas Matthews
A: 

Hi Juha, I just code a simple program multiply two number stored in 2 line in file using algorithm long multiplication. It can multiply two number which have more than 1 billion number in each other

Example:

            23958233
            5830 ×
         ------------
            00000000  ( =      23,958,233 ×     0)
           71874699   ( =      23,958,233 ×    30)
          191665864   ( =      23,958,233 ×   800)
         119791165    ( =      23,958,233 × 5,000)

Source code:

Please review and give your comment http://code.google.com/p/juniormultiply/source/browse/#svn/trunk/src

nguyendat