I was trying to come up with the solution for that ... two large numbers, a
and b
are represented by char[]
or char*
and the goal is to multiply them into a third pointer, char* c
:
void multiply( const char* a, const char* b ){
int len_a = strlen( a );
int len_b = strlen( b );
int* c = new int[ len_a + len_b];
memset( c, 0, sizeof(int) * ( len_a + len_b ));
for( int i = len_a - 1; i >= 0; i-- ){
for( int j = len_b - 1; j >= 0; j-- ){
c[ i + j + 1 ] += ( b[ j ] - '0') * ( a[ i ] - '0' );
}
}
for( int i = len_a + len_b; i >= 0; i-- ){
if( c[ i ] >= 10 ){
c[ i - 1 ] += c[ i ] / 10;
c[ i ] %= 10;
}
}
cout << a << " * " << b << " = " << c << endl;
delete[] c;
}
I wrote the above function to do this operation for me ... however, when I use the inputs:
int main( void ){
const char* a = "999";
const char* b = "99999";
multiply( a, b );
// I expect the answer to be 1 and 6
// profit = 0.92
return 0;
}
I got:
999 * 99999 = 0x100100080
Why am I getting the memory address and not the actual number? Thanks!