write a code for large nos multilication (upto 200 digits)
Answer Posted / ajeet kumar
#include<iostream>
#include<string>
#include<sstream>
#include<vector>
using namespace std;
string toString(int a){
string s="";
stringstream buf;
buf<<a;
s=buf.str();
return s;
}
string ADD( string n1, string n2 ) {
int l1 = n1.size();
int l2 = n2.size();
int d = l1-l2;
d=(d>0)?d:-d;
string s1="";
if( d > 0 ){
for(int i=0;i<d;i++)
s1=s1+'0';
}
if(l1 > l2)
n2=s1+n2;
if(l2>l1)
n1=s1+n1;
int l = n1.size();
int carry = 0;
int x,y,z;
string ans="";
for(int j=l-1;j>=0;j--){
x=(int)n1[j]-48;
y=(int)n2[j]-48;
z=x+y+carry;
if(z>9){
carry=z/10;
string ad = toString(z%10);
ans=ad+ans;
}
else{
carry=0;
string ad = toString(z);
ans=ad+ans;
}
}
if(carry!=0)
ans='1'+ans;
return ans;
}
string remove_leading_zeroes(string tmp) {
string s="0";
for(int i=0;i<tmp.size();i++){
if(tmp[i]=='0')
continue;
tmp=tmp.substr(i,tmp.size()-i+1);
return tmp;
}
return s;
}
vector <string> equate_with_leading_zeros( string a, string
b ) {
int l1=a.size();
int l2=b.size();
int d=(l1-l2>0)?(l1-l2):(l2-l1);
string s="";
vector<string>v;
for(int i=0;i<d;i++)
s=s+'0';
if(l1>l2)
b=s+b;
if(l2>l1)
a=s+a;
v.push_back(a);
v.push_back(b);
return v;
}
string MULTIPLY( string s1, string s2 ) {
vector<string> v = equate_with_leading_zeros(s1,s2);
string a=v[0];
string b=v[1];
string op1,prev="";
int x,y,z;
int l=a.size();
int counter = 0;
int carry=0;
for(int i=l-1;i>=0;i--){
x = (int)a[i]-48;
op1="";
carry = 0;
for(int j=l-1;j>=0;j--){
y = (int)b[j]-48;
z = x*y+carry;
if(z>9){
op1=toString(z%10)+op1;
carry=z/10;
}
else{
op1=toString(z)+op1;
carry=0;
}
}
if(carry != 0){
op1=toString(carry)+op1;
}
carry=0;
string appString="";
for(int k=0;k<counter;k++)
appString=appString+'0';
op1=op1+appString;
prev = ADD(op1,prev);
counter++;
}
if(carry!=0){
prev = toString(carry)+prev;
}
string ans= remove_leading_zeroes(prev);
return ans;
}
int main()
{
string a,b;
cout<<"Enter first no.: ";
cin>>a;
cout<<"Enter second no.: ";
cin>>b;
string ans = MULTIPLY(a,b);
cout<<ans<<"\n";
return 0;
}
| Is This Answer Correct ? | 2 Yes | 0 No |
Post New Answer View All Answers
Why do we use int main instead of void main in c?
How can variables be characterized?
can we implement multi-threads in c.
How does free() know explain how much memory to release?
Explain what are the __date__ and __time__ preprocessor commands?
Where are the auto variables stored?
Which header file is essential for using strcmp function?
What are shell structures used for?
Explain the use of function toupper() with and example code?
What are the primitive data types in c?
How many identifiers are there in c?
Which is better pointer or array?
How can I find out if there are characters available for reading?
What is the best way to store flag values in a program?
Is printf a keyword?