How can I multiply really big numbers c++ - 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?

The result overflows the int (and also std::uint64_t)
You have to use some BigInt library.

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

Use pan paper approach as we used in 2nd standard.
Store two numbers in two different array in reverse order. And take ans array as size of (arr1.size + arr2.size).And also initilize ans array to zero.
In your case
arr1[10]={3,4,4,3,4,2,3,4,3,2},
arr2[15]={4,2,3,4,2,3,,4,5,3,4,5,3,4,6,4,5};
for(int i=0;i<arr1_length;i++)
{
for(int j=0;j<arr2_length;j++)
{
ans[i+j]+=arr1[i]*arr2[j];
ans[i+j+1]=ans[i+j+1]+ans[i+j]/10;
ans[i+j]%=10;
}
}
Then ans array contain the result.Please print carefully ans array. it may contain leading zero.

ints only hold 32 bits. When the result of a multiplication is larger than 2^31 - 1, the result rolls over to a large negative value. Instead of using the int data type, use long long int, which holds 64 bits.

You should first try to use 64-bit numbers (long or better, unsigned long if everything is positive). With unsigned long you can operate between 0 and 18446744073709551615, with long between -9223372036854775808 and 9223372036854775807.
If it is not enough, then there is no easy solution, you have to perform your operation at software level using arrays of unsigned long for instance, and overload "<<" operator for display. But this is not that easy, and I guess you are a beginner (no offense) considering the question you asked.
If 64-bit representation is not enough for you, I think you should consider floating-point representation, especially "double". With double, you can represent numbers between about -10^308 and 10^308. You won't be able to have perfectly accurate computatiosn on very large number (the least significant digits won't be computed), but this should be a good-enough option for whatever you want to do here.

First, you have to make your value long longs
Second, you would want to add a (long long) in front of the multiplication. This is because when you have (ab) it returns an int therefore if you want it to return a long long you would want (long long)(ab).

I would like to elaborate on, and clarify Shravan Kumar's Answer using a full-fledged code. The code starts with a long integers a & b, which are multiplied using array, converted to a string and then back into the long int.
#include <iostream>
#include <string>
#include<algorithm>
using namespace std;
int main()
{
//Numbers to be multiplied
long a=111,b=100;
//Convert them to strings (or character array)
string arr1 = to_string(a), arr2 = to_string(b);
//Reverse them
reverse(arr1.begin(), arr1.end());
reverse(arr2.begin(), arr2.end());
//Getting size for final result, just to avoid dynamic size
int ans_size = arr1.size() + arr2.size();
//Declaring array to store final result
int ans[ans_size]={0};
//Multiplying
//In a reverse manner, just to avoid reversing strings explicitly
for(int i=0; i<arr1.size();i++)
{
for(int j=0; j<arr2.size();j++)
{
//Convert array elements (char -> int)
int p = (int)(arr1[i]) - '0';
int q = (int)(arr2[j]) - '0';
//Excerpt from Shravan's answer above
ans[i+j]+=p*q;
ans[i+j+1]=ans[i+j+1]+ans[i+j]/10;
ans[i+j]%=10;
}
}
//Declare array to store string form of final answer
string s="";
for(auto i=0;i<ans_size; ++i)
s += to_string(ans[i]);
reverse(s.begin(), s.end() );
//If last element is 0, it should be skipped
if(s[0] =='0')
{
string ss(s,1,s.size()-1);
s=ss;
}
//Final answer
cout<< s;
return 0;
}

Use float instead. It can go up to about 3.4028235 × 1038

// its may heplfull for you
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#define MAX 1000
void reverse(char *from, char *to ){
int len=strlen(from);
int l;
for(l=0;l<len;l++)to[l]=from[len-l-1];
to[len]='\0';
}
void call_mult(char *first,char *sec,char *result){
char F[MAX],S[MAX],temp[MAX];
int f_len,s_len,f,s,r,t_len,hold,res;
f_len=strlen(first);
s_len=strlen(sec);
reverse(first,F);
reverse(sec,S);
t_len=f_len+s_len;
r=-1;
for(f=0;f<=t_len;f++)temp[f]='0';
temp[f]='\0';
for(s=0;s<s_len;s++){
hold=0;
for(f=0;f<f_len;f++){
res=(F[f]-'0')*(S[s]-'0') + hold+(temp[f+s]-'0');
temp[f+s]=res%10+'0';
hold=res/10;
if(f+s>r) r=f+s;
}
while(hold!=0){
res=hold+temp[f+s]-'0';
hold=res/10;
temp[f+s]=res%10+'0';
if(r<f+s) r=f+s;
f++;
}
}
for(;r>0 && temp[r]=='0';r--);
temp[r+1]='\0';
reverse(temp,result);
}
int main(){
char fir[MAX],sec[MAX],res[MAX];
while(scanf("%s%s",&fir,&sec)==2){
call_mult(fir,sec,res);
int len=strlen(res);
for(int i=0;i<len;i++)printf("%c",res[i]);
printf("\n");
}
return 0;
}

You can use queue data structure to find the product of two really big numbers with O(n*m). n and m are the number of digits in a number.

Related

Multiply 2 1000-digit binary numbers in C++ [duplicate]

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?
The result overflows the int (and also std::uint64_t)
You have to use some BigInt library.
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
Use pan paper approach as we used in 2nd standard.
Store two numbers in two different array in reverse order. And take ans array as size of (arr1.size + arr2.size).And also initilize ans array to zero.
In your case
arr1[10]={3,4,4,3,4,2,3,4,3,2},
arr2[15]={4,2,3,4,2,3,,4,5,3,4,5,3,4,6,4,5};
for(int i=0;i<arr1_length;i++)
{
for(int j=0;j<arr2_length;j++)
{
ans[i+j]+=arr1[i]*arr2[j];
ans[i+j+1]=ans[i+j+1]+ans[i+j]/10;
ans[i+j]%=10;
}
}
Then ans array contain the result.Please print carefully ans array. it may contain leading zero.
ints only hold 32 bits. When the result of a multiplication is larger than 2^31 - 1, the result rolls over to a large negative value. Instead of using the int data type, use long long int, which holds 64 bits.
You should first try to use 64-bit numbers (long or better, unsigned long if everything is positive). With unsigned long you can operate between 0 and 18446744073709551615, with long between -9223372036854775808 and 9223372036854775807.
If it is not enough, then there is no easy solution, you have to perform your operation at software level using arrays of unsigned long for instance, and overload "<<" operator for display. But this is not that easy, and I guess you are a beginner (no offense) considering the question you asked.
If 64-bit representation is not enough for you, I think you should consider floating-point representation, especially "double". With double, you can represent numbers between about -10^308 and 10^308. You won't be able to have perfectly accurate computatiosn on very large number (the least significant digits won't be computed), but this should be a good-enough option for whatever you want to do here.
First, you have to make your value long longs
Second, you would want to add a (long long) in front of the multiplication. This is because when you have (ab) it returns an int therefore if you want it to return a long long you would want (long long)(ab).
I would like to elaborate on, and clarify Shravan Kumar's Answer using a full-fledged code. The code starts with a long integers a & b, which are multiplied using array, converted to a string and then back into the long int.
#include <iostream>
#include <string>
#include<algorithm>
using namespace std;
int main()
{
//Numbers to be multiplied
long a=111,b=100;
//Convert them to strings (or character array)
string arr1 = to_string(a), arr2 = to_string(b);
//Reverse them
reverse(arr1.begin(), arr1.end());
reverse(arr2.begin(), arr2.end());
//Getting size for final result, just to avoid dynamic size
int ans_size = arr1.size() + arr2.size();
//Declaring array to store final result
int ans[ans_size]={0};
//Multiplying
//In a reverse manner, just to avoid reversing strings explicitly
for(int i=0; i<arr1.size();i++)
{
for(int j=0; j<arr2.size();j++)
{
//Convert array elements (char -> int)
int p = (int)(arr1[i]) - '0';
int q = (int)(arr2[j]) - '0';
//Excerpt from Shravan's answer above
ans[i+j]+=p*q;
ans[i+j+1]=ans[i+j+1]+ans[i+j]/10;
ans[i+j]%=10;
}
}
//Declare array to store string form of final answer
string s="";
for(auto i=0;i<ans_size; ++i)
s += to_string(ans[i]);
reverse(s.begin(), s.end() );
//If last element is 0, it should be skipped
if(s[0] =='0')
{
string ss(s,1,s.size()-1);
s=ss;
}
//Final answer
cout<< s;
return 0;
}
Use float instead. It can go up to about 3.4028235 × 1038
// its may heplfull for you
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#define MAX 1000
void reverse(char *from, char *to ){
int len=strlen(from);
int l;
for(l=0;l<len;l++)to[l]=from[len-l-1];
to[len]='\0';
}
void call_mult(char *first,char *sec,char *result){
char F[MAX],S[MAX],temp[MAX];
int f_len,s_len,f,s,r,t_len,hold,res;
f_len=strlen(first);
s_len=strlen(sec);
reverse(first,F);
reverse(sec,S);
t_len=f_len+s_len;
r=-1;
for(f=0;f<=t_len;f++)temp[f]='0';
temp[f]='\0';
for(s=0;s<s_len;s++){
hold=0;
for(f=0;f<f_len;f++){
res=(F[f]-'0')*(S[s]-'0') + hold+(temp[f+s]-'0');
temp[f+s]=res%10+'0';
hold=res/10;
if(f+s>r) r=f+s;
}
while(hold!=0){
res=hold+temp[f+s]-'0';
hold=res/10;
temp[f+s]=res%10+'0';
if(r<f+s) r=f+s;
f++;
}
}
for(;r>0 && temp[r]=='0';r--);
temp[r+1]='\0';
reverse(temp,result);
}
int main(){
char fir[MAX],sec[MAX],res[MAX];
while(scanf("%s%s",&fir,&sec)==2){
call_mult(fir,sec,res);
int len=strlen(res);
for(int i=0;i<len;i++)printf("%c",res[i]);
printf("\n");
}
return 0;
}
You can use queue data structure to find the product of two really big numbers with O(n*m). n and m are the number of digits in a number.

efficiency of using stringstream to convert string to int?

Is the code below less (or more, or equally) efficient than:
make substring from cursor
make stringstream from substring
extract integer using stream operator
? (question edit) or is it less (or more, or equally) efficient than:
std::stoi
? and why?
Could this function be made more efficient?
(The class brings these into scope:)
std::string expression // has some numbers and other stuff in it
int cursor // points somewhere in the string
The code:
int Foo_Class::read_int()
{
/** reads an integer out of the expression from the cursor */
// make stack of digits
std::stack<char> digits;
while (isdigit(expression[cursor])) // this is safe, returns false, for the end of the string (ISO/IEC 14882:2011 21.4.5)
{
digits.push(expression[cursor] - 48); // convert from ascii
++cursor;
}
// add up the stack of digits
int total = 0;
int exponent = 0; // 10 ^ exponent
int this_digit;
while (! digits.empty())
{
this_digit = digits.top();
for (int i = exponent; i > 0; --i)
this_digit *= 10;
total += this_digit;
++exponent;
digits.pop();
}
return total;
}
(I know it doesn't handle overflow.)
(I know someone will probably say something about the magic numbers.)
(I tried pow(10, exponent) and got incorrect results. I'm guessing because of floating point arithmetic, but not sure why because all the numbers are integers.)
I find using std::stringstream to convert numbers is really quite slow.
Better to use the many dedicated number conversion functions like std::stoi, std::stol, std::stoll. Or std::strtol, std::strtoll.
I found lots of information on this page:
http://www.kumobius.com/2013/08/c-string-to-int/
As Galik said, std::stringstream is very slow compared to everything else.
std::stoi is much faster than std::stringstream
The manual code can be faster still, but as has been pointed out, it doesn't do all the error checking and could have problems.
This website also has an improvement over the code above, multiplying the total by 10, instead of the digit before it's added to the total (in sequential order, instead of reverse, with the stack). This makes for less multiplying by 10.
int Foo_Class::read_int()
{
/** reads an integer out of the expression from the cursor */
int to_return = 0;
while (isdigit(expression[cursor])) // this is safe, returns false, for the end of the string (ISO/IEC 14882:2011 21.4.5)
{
to_return *= 10;
to_return += (expression[cursor] - '0'); // convert from ascii
++cursor;
}
return to_return;
}

Fast Popcount instruction or Hamming distance for binary array?

I'm implementing on Visual Studio 2010 C++
I have two binary arrays. For example,
array1[100] = {1,0,1,0,0,1,1, .... }
array2[100] = {0,0,1,1,1,0,1, .... }
To calculate the Hamming distance between array1 and array2,
array3[100] stores the xor result of array1 and array2.
Then I have to count the number of 1 bits in array3. To do this, I know I can use the __popcnt instruction.
For now, I'm doing something like below:
popcnt_result = 0;
for (i=0; i<100; i++) {
popcnt_result = popcnt_result + __popcnt(array3[i]);
}
It shows a good result but is slow. How can I make it faster?
array3 seems a bit wasteful, you're accessing a whole extra 400 bytes of memory that you don't need to. I would try comparing what you have with the following:
for (int i = 0; i < 100; ++i) {
result += (array1[i] ^ array2[i]); // could also try != in place of ^
}
If that helps at all, then I leave it as an exercise for the reader how to apply both this change and duskwuff's.
As implemented, the __popcnt call is not helping. It's actually slowing you down.
__popcnt counts the number of set bits in its argument. You're only passing in one element, which looks like it's guaranteed to be 0 or 1, so the result (also 0 or 1) is not useful. Doing this would be slightly faster:
popcnt_result += array3[i];
Depending on how your array is laid out, you may or may not be able to use __popcnt in a cleverer way. Specifically, if your array consists of one-byte elements (e.g, char, bool, int8_t, or similar), you could perform a population count on four elements at a time:
for(i = 0; i < 100; i += 4) {
uint32_t *p = (uint32_t *) &array3[i];
popcnt_result += __popcnt(*p);
}
(Note that this depends on the fact that 100 is divisible evenly by 4. You'd have to add some special-case handling for the last few elements otherwise.)
If the array consists of larger values, such as int, though, you're out of luck, and there's still no guarantee that this will be any faster than the naïve implementation above.
If your arrays only contain two values (0 or 1) the Hamming distance is just the number of positions where corresponding values are different. This can be done in one pass using std::inner_product from the standard library.
#include <iostream>
#include <functional>
#include <numeric>
int main()
{
int array1[100] = { 1,0,1,0,0,1,1, ... };
int array2[100] = { 0,0,1,1,1,0,1, ... };
int distance = std::inner_product(array1, array1 + 100, array2, 0, std::plus<int>(), std::not_equal_to<int>());
std::cout << "distance=" << distance << '\n';
return 0;
}

Convert Int to Char Array

I need to make a class called MyInt which handles any size positive numbers by creating an int array. I am making a constructor to be used in converting an int (any size supported by ints) into a MyInt. I need to convert the int into a char array and then read digit by digit into the int array. So my question is, without using any libraries except <iostream> <iomanip> and <cstring> how can I convert an int with multiple digits into a character array?
You don't need to make a char array as an intermediary step. The digits (I assume in base 10) can be obtained one by one using modulo 10 operations. Something like:
convert(int *ar, const int i)
{
int p, tmp;
tmp = i
while (tmp != 0)
{
ar[p] = tmp % 10;
tmp = (tmp - ar[p])/10;
p++;
}
}
Not sure if this is what you want, but:
int myInt = 30;
char *chars = reinterpret_cast<char*>(&myInt);
And you can get the 4 separate char's:
chars[0]; // is the first char
chars[1]; // is the second char
chars[2]; // is the third char, and
chars[3]; // is the fourth/last char
...but I'm not entirely sure if that's what you are looking for.
One possible way of doing that conversion with such restraints is as follows:
function convert:
//find out length of integer (integer division works well)
//make a char array of a big enough size (including the \0 if you need to print it)
//use division and modulus to fill in the array one character at a time
//if you want readable characters, don't forget to adjust for them
//don't forget to set the null character if you need it
I hope I didn't misunderstand your question, but that worked for me, giving me a printable array that read the same as the integer itself.

How to convert large integers to base 2^32?

First off, I'm doing this for myself so please don't suggest "use GMP / xint / bignum" (if it even applies).
I'm looking for a way to convert large integers (say, OVER 9000 digits) into a int32 array of 232 representations. The numbers will start out as base 10 strings.
For example, if I wanted to convert string a = "4294967300" (in base 10), which is just over INT_MAX, to the new base 232 array, it would be int32_t b[] = {1,5}. If int32_t b[] = {3,2485738}, the base 10 number would be 3 * 2^32 + 2485738. Obviously the numbers I'll be working with are beyond the range of even int64 so I can't exactly turn the string into an integer and mod my way to success.
I have a function that does subtraction in base 10. Right now I'm thinking I'll just do subtraction(char* number, "2^32") and count how many times before I get a negative number, but that will probably take a long time for larger numbers.
Can someone suggest a different method of conversion? Thanks.
EDIT
Sorry in case you didn't see the tag, I'm working in C++
Assuming your bignum class already has multiplication and addition, it's fairly simple:
bignum str_to_big(char* str) {
bignum result(0);
while (*str) {
result *= 10;
result += (*str - '0');
str = str + 1;
}
return result;
}
Converting the other way is the same concept, but requires division and modulo
std::string big_to_str(bignum num) {
std::string result;
do {
result.push_back(num%10);
num /= 10;
} while(num > 0);
std::reverse(result.begin(), result.end());
return result;
}
Both of these are for unsigned only.
To convert from base 10 strings to your numbering system, starting with zero continue adding and multiplying each base 10 digit by 10. Every time you have a carry add a new digit to your base 2^32 array.
The simplest (not the most efficient) way to do this is to write two functions, one to multiply a large number by an int, and one to add an int to a large number. If you ignore the complexities introduced by signed numbers, the code looks something like this:
(EDITED to use vector for clarity and to add code for actual question)
void mulbig(vector<uint32_t> &bignum, uint16_t multiplicand)
{
uint32_t carry=0;
for( unsigned i=0; i<bignum.size(); i++ ) {
uint64_t r=((uint64_t)bignum[i] * multiplicand) + carry;
bignum[i]=(uint32_t)(r&0xffffffff);
carry=(uint32_t)(r>>32);
}
if( carry )
bignum.push_back(carry);
}
void addbig(vector<uint32_t> &bignum, uint16_t addend)
{
uint32_t carry=addend;
for( unsigned i=0; carry && i<bignum.size(); i++ ) {
uint64_t r=(uint64_t)bignum[i] + carry;
bignum[i]=(uint32_t)(r&0xffffffff);
carry=(uint32_t)(r>>32);
}
if( carry )
bignum.push_back(carry);
}
Then, implementing atobignum() using those functions is trivial:
void atobignum(const char *str,vector<uint32_t> &bignum)
{
bignum.clear();
bignum.push_back(0);
while( *str ) {
mulbig(bignum,10);
addbig(bignum,*str-'0');
++str;
}
}
I think Docjar: gnu/java/math/MPN.java might contain what you're looking for, specifically the code for public static int set_str (int dest[], byte[] str, int str_len, int base).
Start by converting the number to binary. Starting from the right, each group of 32 bits is a single base2^32 digit.