Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I multiply really big numbers c++

I have the following code

int i, a, z;  
i = 2343243443;  
a = 5464354324324324;  
z = i * a;  
cout << z << endl;  

When these are multiplied it gives me -1431223188 which is not the answer. How can I make it give me the correct answer?

like image 372
Fred Roy Avatar asked Oct 25 '14 00:10

Fred Roy


People also ask

How do you multiply very large numbers?

How Does it Work? Multiplying large numbers together is performed by multiplying the ones digit of the bottom number to the entire top number. After the ones place value has finished multiplying, move to the tens place value in the bottom number and multiply that digit by the top number.

How do you deal with big numbers in C?

Usually, you would choose a base that is half the largest representable type so that there are no overflows. For instance, in modern C, you would choose uint32_t and do all the digit arithmetic in uint64_t . And don't forget: make the digit type unsigned so that there are no surprises.

How do you multiply numbers in C?

Program to Multiply Two Numbersprintf("Enter two numbers: "); scanf("%lf %lf", &a, &b); Then, the product of a and b is evaluated and the result is stored in product . product = a * b; Finally, product is displayed on the screen using printf() .


2 Answers

The result overflows the int (and also std::uint64_t)

You have to use some BigInt library.

like image 125
Jarod42 Avatar answered Sep 30 '22 20:09

Jarod42


As Jarod42 suggested is perfectly okay, but i am not sure whether overflow will take place or not ?

Try to store each and every digit of number in an array and after that multiply. You will definitely get the correct answer.

For more detail how to multiply using array follow this post http://discuss.codechef.com/questions/7349/computing-factorials-of-a-huge-number-in-cc-a-tutorial

like image 41
Shravan40 Avatar answered Sep 30 '22 21:09

Shravan40