Multiplying two number arrays
Can anyone please tell m开发者_JS百科e 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.
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);
If you want to use the paper-and-pencil arithmetics and don't know how to do that, here is the illustration.
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
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.
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.
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.
精彩评论