From this post: Compare two string as numeric value
I did not get a result.
Please open this post so that someone can answer my question.
I wrote this library (pr.h):
#include <iostream>
#include <string>
#include <bits/stdc++.h>
using namespace std;
class BigNum {
private:
string doSum(string a, string b)
{
if(a.size() < b.size())
swap(a, b);
int j = a.size()-1;
for(int i=b.size()-1; i>=0; i--, j--)
a[j]+=(b[i]-'0');
for(int i=a.size()-1; i>0; i--)
{
if(a[i] > '9')
{
int d = a[i]-'0';
a[i-1] = ((a[i-1]-'0') + d/10) + '0';
a[i] = (d%10)+'0';
}
}
if(a[0] > '9')
{
string k;
k+=a[0];
a[0] = ((a[0]-'0')%10)+'0';
k[0] = ((k[0]-'0')/10)+'0';
a = k+a;
}
return a;
}
bool isSmaller(string str1, string str2)
{
int n1 = str1.length(), n2 = str2.length();
if (n1 < n2)
return true;
if (n2 < n1)
return false;
for (int i = 0; i < n1; i++) {
if (str1[i] < str2[i])
return true;
else if (str1[i] > str2[i])
return false;
}
return false;
}
string findDiff(string str1, string str2)
{
if (isSmaller(str1, str2))
swap(str1, str2);
string str = "";
int n1 = str1.length(), n2 = str2.length();
int diff = n1 - n2;
int carry = 0;
for (int i = n2 - 1; i >= 0; i--) {
int sub = ((str1[i + diff] - '0') - (str2[i] - '0')
- carry);
if (sub < 0) {
sub = sub + 10;
carry = 1;
}
else
carry = 0;
str.push_back(sub + '0');
}
for (int i = n1 - n2 - 1; i >= 0; i--) {
if (str1[i] == '0' && carry) {
str.push_back('9');
continue;
}
int sub = ((str1[i] - '0') - carry);
if (i > 0 || sub > 0)
str.push_back(sub + '0');
carry = 0;
}
reverse(str.begin(), str.end());
return str;
}
public:
string num;
BigNum () {
num = "";
}
BigNum (string tmp) {
num = tmp;
}
string operator +(BigNum a1) {
return doSum(this->num,a1.num);
}
void operator = (BigNum * a1) {
this-> num = a1-> num;
}
void operator = (string tmp) {
this-> num = tmp;
}
bool operator > (BigNum a1) {
if (this->num>a1.num){
return true;
}
else{
return false;
}
}
bool operator < (BigNum a1) {
if (this->num<a1.num){
return true;
}
else{
return false;
}
}
string operator - (BigNum a1) {
return findDiff(this->num, a1.num);
}
friend ostream &operator<<( ostream &output, const BigNum &D ) {
output << D.num;
return output;
}
friend istream &operator>>( istream &input, BigNum &D ) {
input >> D.num;
return input;
}
string operator -=(string tmp){
this->num=findDiff(this->num, tmp);
return this->num;
}
};
And this code:
// C++ program for implementation of Bubble sort
#include "pr.h"
#include <bits/stdc++.h>
using namespace std;
void swap(BigNum *xp, BigNum *yp)
{
BigNum temp = *xp;
*xp = *yp;
*yp = temp;
}
// A function to implement bubble sort
void bubbleSort(BigNum arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
/* Function to print an array */
void printArray(BigNum arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
// Driver code
int main()
{
BigNum arr[5];
arr[0]="5";
arr[1]="5";
arr[2]="1";
arr[3]="3";
arr[4]="8";
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
cout<<"Sorted array: \n";
printArray(arr, n);
return 0;
}
My problem is that this program can only sort 1-digit numbers and gives errors for multi-digit numbers
Example:
This code:
BigNum arr [5];
arr [0] = "100";
arr [1] = "5";
arr [2] = "1";
arr [3] = "3";
arr [4] = "8";
int n = sizeof (arr) / sizeof (arr [0]);
bubbleSort (arr, n);
cout << "Sorted array: \ n";
printArray (arr, n);
Prints this value:
1 100 3 5 8
bool operator < (BigNum a1) is calling std::string:: operator<, thus you getting lexicographical order. The operators < and > should call isSmaller.
bool operator > (const BigNum& a1) const {
return !isSmaller(a1) && num != a1.num;
}
bool operator < (const BigNum& a1) const {
return isSmaller(a1);
}
Do not use constructions
if (smth) return true else return false. You already get true or false in smth, use return smth.
Related
In one of the largest cities in Bytland, Bytesburg, construction of the second stage of the metro is underway. During the construction of the first stage, N stations were built that were not interconnected. According to the master plan, the metro in Bytesburg should consist of no more than two lines. each metro line is straight. The president of the company responsible for laying the lines wants to make sure that no more than two metro lines can be laid, so that all stations built lie on at least one of the two
Exaple 1
input:
6
0 1
1 1
2 1
0 2
1 3
2 2
output:
no
Example 2
input:
6
2 2
4 6
1 0
2 1
6 1
1 1
output:
yes
I wrote the code, but on the seventh test on the testing system, it gives the wrong answer. Help me please. This is my code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct line {
int k, b;
bool x = false;
long long c = 0;
};
int n;
vector<line> lines;
vector<pair<int, int>> p;
bool Is3PointsOnLine(pair<float, float> p1, pair<float, float> p2, pair<float, float> p3) {
return ((p3.first - p1.first)*(p2.second - p1.second) == (p3.second - p1.second)*(p2.first - p1.first));
}
bool PointIsOnLine(line l, int x, int y) {
if (!l.x) {
if (y == ((l.k * x) + l.b))
return true;
}
else {
if (x == l.b)
return true;
}
return false;
}
line f(pair<int, int> c1, pair<int, int> c2) {
int x1 = c1.first;
int y1 = c1.second;
int x2 = c2.first;
int y2 = c2.second;
line ans;
if (x2 != x1) {
ans.k = (y2 - y1) / (x2 - x1);//fix
ans.b = -(x1 * y2 - x1 * y1 - x2 * y1 + x1 * y1) / (x2 - x1);
ans.x = false;
ans.c = 0;
}
else {
ans.k = 0;
ans.b = x1;
ans.x = true;
ans.c = 0;
}
return ans;
}
int a() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (j != i) {
for (int k = 0; k < n; k++) {
if ((k != i) && (k != j) && (Is3PointsOnLine(p[i], p[j], p[k]))) {
lines.push_back(f(p[i], p[j]));
return 0;
}
}
}
}
}
}
int main() {
cin >> n;
p.resize(n);
vector<int> not_used;
for (int i = 0; i < n; i++)
cin >> p[i].first >> p[i].second;
if (n < 5) {
cout << "yes";
return 0;
}
else {
a();
if (lines.size() == 0) {
cout << "no";
return 0;
}
pair<int, int> e = { -8,-8 };
for (int i = 0; i < n; i++) {
if (PointIsOnLine(lines[0], p[i].first, p[i].second)) {
lines[0].c++;
}
else if (e.first == -8) {
e.first = i;
}
else if (e.second == -8) {
e.second = i;
lines.push_back(f(p[e.first], p[e.second]));
for (int j = 0; j <= i; j++) {
if (PointIsOnLine(lines[1], p[j].first, p[j].second)) {
lines[1].c++;
}
}
e = { -5,-5 };
}
else if (PointIsOnLine(lines[1], p[i].first, p[i].second)) {
lines[1].c++;
}
else {
cout << "no";
return 0;
}
}
if (lines[0].c+1 >= n && e.first != -2 && e.second == -8) {
cout << "yes";
return 0;
}
else if (lines[0].c + lines[1].c >= n) {
cout << "yes";
return 0;
}
else {
cout << "no";
return 0;
}
}
return 0;
}
Code v2
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct line {
pair<int, int> p1, p2;
long long c = 0;
};
int n;
vector<line> lines;
vector<pair<int, int>> p;
bool Is3PointsOnLine(pair<float, float> p1, pair<float, float> p2, pair<float, float> p3) {
return ((p3.first - p1.first)*(p2.second - p1.second) == (p3.second - p1.second)*(p2.first - p1.first));
}
//лежит ли точка на прямой
bool PointIsOnLine(line l, int x, int y) {
return Is3PointsOnLine(l.p1, l.p2, {x , y});
}
int a() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (j != i) {
for (int k = 0; k < n; k++) {
if ((k != i) && (k != j) && (Is3PointsOnLine(p[i], p[j], p[k]))) {
line sdafsadf;
sdafsadf.p1 = p[i]; sdafsadf.p2 = p[j];
lines.push_back(sdafsadf);
return 0;
}
}
}
}
}
}
int main() {
cin >> n;
p.resize(n);
vector<int> not_used;
for (int i = 0; i < n; i++)
cin >> p[i].first >> p[i].second;
if (n < 5) {
cout << "yes";
return 0;
}
else {
//ищем первую прямую
a();
if (lines.size() == 0) {
cout << "no";
return 0;
}
pair<int, int> e = { -8,-8 };
for (int i = 0; i < n; i++) {
if (PointIsOnLine(lines[0], p[i].first, p[i].second)) {
lines[0].c++;
}
else if (e.first == -8) {
e.first = i;
}
else if (e.second == -8) {
e.second = i;
line sdafsadf;
sdafsadf.p1 = p[e.first]; sdafsadf.p2 = p[e.second];
lines.push_back(sdafsadf);
for (int j = 0; j <= i; j++) {
if (PointIsOnLine(lines[1], p[j].first, p[j].second)) {
lines[1].c++;
}
}
e = { -5,-5 };
}
else if (PointIsOnLine(lines[1], p[i].first, p[i].second)) {
lines[1].c++;
}
else {
cout << "no";
return 0;
}
}
if (lines[0].c+1 >= n && e.first != -2 && e.second == -8) {
cout << "yes";
return 0;
}
else if ((lines[0].c + lines[1].c >= n) && (lines[0].p1 != lines[1].p1) && (lines[0].p1 != lines[1].p2) && (lines[0].p2 != lines[1].p1) && (lines[0].p2 != lines[1].p2)) {
cout << "yes";
return 0;
}
else {
cout << "no";
return 0;
}
}
return 0;
}
Your function f is horribly broken because it uses integer division. Then everything after that which relies on k and b, including PointIsOnLine, will give wrong results. Is3PointsOnLine seems ok, change your line struct to store two points, not slope+intercept, and then PointInOnLine can just call Is3PointsOnLine.
I'm amazed that you passed any non-trivial test cases with such a bug.
This also will not work
if (lines[0].c + lines[1].c >= n)
because you aren't testing that lines[1] isn't a duplicate of lines[0].
Also, you can reach lines[0].c + lines[1].c == n and still miss one station completely, if another station lies at the intersection of the lines and gets double-counted.
My program should read input as an integer for the length followed by (sufficiently) parenthesized floats and simple operators and output the value of the expression. For example, if the input were 11 1 + 2 ^ 3 / 4 * 5 - 6, the result should be equal to (1 + (((2 ^ 3) / 4) * 5)) - 6, or 5. However, even when I input 5 1 + 2 + 3, the output is 5 instead of 6. I think this might be because of the many vector assignments, in particular the marked line (I found this while debugging).
My code (sorry if it is not self explanatory):
#include <iostream>
#include <string>
#include <vector>
#include <cmath>
using namespace std;
float op(char op, float x, float y)
{
switch (op)
{
case '+':
{
return x+y;
break;
}
case '-':
{
return x-y;
break;
}
case '*':
{
return x*y;
break;
}
case '/':
{
return x/y;
break;
}
case '^':
{
return pow(x,y);
break;
}
default:
{
cout << "Error: bad input ";
return 0;
}
}
}
float nopars(vector<string> stack, int stackl, vector<char> ops, int opsr)
{
int len = stackl, opsrr = opsr;
vector<string> nstack, nnstack;
vector<char> nops = ops, nnops;
nstack = stack;
while (opsrr != 0)
{
string s1 (1, nops[0]);
for (int i = 0; i < len; i++)
{
if (nstack[i] == s1)
{
for (int j = 0; j < len - 2; j++)
{
nnstack = {};
if (j == i-1)
{
nnstack.push_back(to_string(op(nops[0], stof(nstack[i-1]), stof(nstack[i+1]))));
}
else if (j < i-1)
{
nnstack.push_back(nstack[j]);
}
else if (j > i-1)
{
nnstack.push_back(nstack[j+2]);
}
}
len = len - 2;
nstack = nnstack; //I think this is wrong?
i--;
}
}
nnops = {};
for (int i = 0; i < opsr-1; i++)
{
nnops.push_back(nops[i+1]);
}
opsrr--;
nops = nnops;
}
return stof(nstack[0]);
}
float all(vector<string> stack, int stackl, vector<char> ops, int opsr)
{
int t1 = 0, t2 = 0;
int len = stackl;
int nprs;
vector<string> nstack, nnstack, nstck;
nstack = stack;
while (true)
{
nprs = 0;
for (int i = 0; i < len; i++)
{
if (nstack[i] == "(")
{
nprs = 1;
t1 = i;
}
else if (nstack[i] == ")")
{
nprs = 1;
t2 = i;
nstck = {};
for (int j = t1 + 1; j < t2; j++)
{
nstck.push_back(nstack[j]);
}
for (int j = 0; j < len - t2 + t1; j++)
{
if (j == t1)
{
nnstack.push_back(to_string(nopars(nstck, t2-t1-1, ops, opsr)));
}
else if (j < t1)
{
nnstack.push_back(nstack[j]);
}
else if (j > t1)
{
nnstack.push_back(nstack[j+t2-t1]);
}
}
len = len - t2 + t1;
break;
}
}
if (nprs == 0)
{
break;
}
nstack = nnstack;
}
return nopars(nstack, len, ops, opsr);
}
void calculate()
{
vector<string> stack;
int stackl;
string t;
cin >> stackl;
for (int i = 0; i < stackl; i++)
{
cin >> t;
stack.push_back(t);
}
cout << all(stack, stackl, {'^', '/', '*', '-', '+'}, 5);
}
int main()
{
calculate();
return 0;
}
A binary recurrent LL parser
#include <iostream>
#include <string>
#include <sstream>
#include <functional>
#include <iterator>
#include <cmath>
#include <map>
using namespace std;
using T = float;
map< int, map<std::string, std::function<T(const T&, const T&)> > > m_foo =
{ {1, { { "+", std::plus<T>() }, { "-", std::minus<T>() } } },
{2, { { "*", std::multiplies<T>() }, { "/", std::divides<T>() } } },
{3, { { "^", powf } } } };
T calc_ll(istream_iterator<string>& t, int level) {
if ( !m_foo.contains(level) ) return std::stof(*t++);
auto result = calc_ll(t, level+1);
auto l = m_foo[level];
while ( l.find(*t) != l.end() ) {
auto foo = l.find(*t)->second;
result = foo(result, calc_ll(++t, level+1) );
}
return result;
}
int main()
{
std::stringstream ss(std::string("1 + 2 ^ 3 / 4 * 5 - 6"));
auto t = istream_iterator<string>(ss);
cout << "result : " << calc_ll( t, 1 );
return 0;
}
link https://godbolt.org/z/9vPMGn
It seems the error is in the unintentionally repeated declaration nnstack = {}.
#include <iostream>
#include <string>
#include <vector>
#include <cmath>
using namespace std;
float op(char op, float x, float y)
{
switch (op)
{
case '+':
{
return x+y;
break;
}
case '-':
{
return x-y;
break;
}
case '*':
{
return x*y;
break;
}
case '/':
{
return x/y;
break;
}
case '^':
{
return pow(x,y);
break;
}
default:
{
cout << "Error: bad input ";
return 0;
}
}
}
float nopars(vector<string> stack, int stackl, vector<char> ops, int opsr)
{
int len = stackl, opsrr = opsr;
vector<string> nstack, nnstack;
vector<char> nops = ops, nnops;
nstack = stack;
while (opsrr != 0)
{
string s1 (1, nops[0]);
for (int i = 0; i < len; i++)
{
if (nstack[i] == s1)
{
nnstack = {}; //this was missing
for (int j = 0; j < len - 2; j++)
{
//nnstack = {}; //this was misplaced
if (j == i-1)
{
nnstack.push_back(to_string(op(nops[0], stof(nstack[i-1]), stof(nstack[i+1]))));
}
else if (j < i-1)
{
nnstack.push_back(nstack[j]);
}
else if (j > i-1)
{
nnstack.push_back(nstack[j+2]);
}
}
len = len - 2;
nstack = nnstack;
i--;
}
}
nnops = {};
for (int i = 0; i < opsr-1; i++)
{
nnops.push_back(nops[i+1]);
}
opsrr--;
nops = nnops;
}
return stof(nstack[0]);
}
float all(vector<string> stack, int stackl, vector<char> ops, int opsr)
{
int t1 = 0, t2 = 0;
int len = stackl;
int nprs;
vector<string> nstack, nnstack, nstck;
nstack = stack;
while (true)
{
nprs = 0;
for (int i = 0; i < len; i++)
{
if (nstack[i] == "(")
{
nprs = 1;
t1 = i;
}
else if (nstack[i] == ")")
{
nprs = 1;
t2 = i;
nstck = {};
for (int j = t1 + 1; j < t2; j++)
{
nstck.push_back(nstack[j]);
}
for (int j = 0; j < len - t2 + t1; j++)
{
if (j == t1)
{
nnstack.push_back(to_string(nopars(nstck, t2-t1-1, ops, opsr)));
}
else if (j < t1)
{
nnstack.push_back(nstack[j]);
}
else if (j > t1)
{
nnstack.push_back(nstack[j+t2-t1]);
}
}
len = len - t2 + t1;
break;
}
}
if (nprs == 0)
{
break;
}
nstack = nnstack;
}
return nopars(nstack, len, ops, opsr);
}
void calculate()
{
vector<string> stack;
int stackl;
string t;
cin >> stackl;
for (int i = 0; i < stackl; i++)
{
cin >> t;
stack.push_back(t);
}
cout << all(stack, stackl, {'^', '/', '*', '-', '+'}, 5);
}
int main()
{
calculate();
return 0;
}
I have a recursive void method which is written in c++. How can I exit from this recursive method when I get my needed value.
#include<bits/stdc++.h>
using namespace std;
int a[25];
char x[25];
int n, m ;
string s;
void go(int pos)
{
if(pos == n - 1)
{
int suma = a[0];
for(int i = 0 ; i < n - 1;i++)
{
if(x[i] == '+')suma += a[i + 1];
else suma -= a[i + 1];
}
//here I need hint how to close this method when suma will equal to m
//if(suma == x) here I should break this method
return ;
}
x[pos] = '+';
go(pos+1);
x[pos] = '-';
go(pos+1);
}
main()
{
cin >> n >> m;
for(int i = 0 ; i < n;i++)
cin >> a[i];
go(0);
for(int i = 0 ; i < n- 1;i++)
cout << x[i]<<" ";
}
I need to hint how to break void method when my summa will equal to x data everything was declared please do you know some hint for closing this method and I should get value of x arrays.
Throw where you have found your result, and catch at the initial call site
#include <string>
#include <iostream>
int a[25];
char x[25];
int n, m ;
std::string s;
struct result_found{};
void go(int pos)
{
if(pos == n - 1)
{
int suma = a[0];
for(int i = 0; i < n - 1; i++)
{
if(x[i] == '+')suma += a[i + 1];
else suma -= a[i + 1];
}
if (suma == m)
throw result_found{};
}
x[pos] = '+';
go(pos+1);
x[pos] = '-';
go(pos+1);
}
main()
{
std::cin >> n >> m;
for(int i = 0 ; i < n;i++)
std::cin >> a[i];
try {
go(0);
}
catch (result_found&) {}
for(int i = 0 ; i < n- 1;i++)
std::cout << x[i] << " ";
}
You may use an 'static bool' flag on the method.
static fields on functions keep their value between several functions calls.
void go(int pos)
{
static bool found=false;
if (found) return;
//rest of your code here...
//of course when you found what are you searching, do found = true;
}
i was looking around the forums and i still couldnt find my answer to my problem.
I got two strings, that are just really an array of numbers. for example(i just choose random numbers
string input1="12345678909876543212";
string input2="12345";
I want to add these two string together but act them like there integers.
My goal is creating a class where i can add bigger numbers than (long long int) so it can exceed the largest long long int variable.
So i revese the string with no problem, so now there
input1="21234567890987654321"
input2="54321"
then i tried adding, let's say input1[0]+input2[0] (2+5) to a new string lets call it newString[0] where that would equal (7); but i cant find a good way to temporally convert the current number in the string so i can add it to the new string? can anyone help. I get sick and tired of atoi,stof,stod. they don't seem to work at all for me.
Any way i can make this function work.
I don't care about making the class yet, i just care about finding a way to add those two strings mathematically but still maintaining the newString's string format. Thank you for whoever can figure this out for me
Okay, so, assuming your only problem is with the logic, not the class design thing, I came up with this logic
fill up the inputs with 0s, checking the lengths, match the lengths
add like normal addition, keeping track of carry
finally remove leading zeros from result
So using std::transform with a lambda function on reverse iterators :-
char carry = 0;
std::transform(input1.rbegin(),input1.rend(),input2.rbegin(),
result.rbegin(),[&carry]( char x, char y){
char z = (x-'0')+(y-'0') + carry;
if (z > 9)
{
carry = 1;
z -= 10;
}
else
{
carry = 0;
}
return z + '0';
});
//And finally the last carry
result[0] = carry + '0';
//Remove the leading zero
n = result.find_first_not_of("0");
if (n != string::npos)
{
result = result.substr(n);
}
See Here
Edit "Can you comment on what your doing here"
+--------+--------------+------------+-------> Reverse Iterator
| | | |
std::transform( | input1.rbegin(), input1.rend(),input2.rbegin(),
result.rbegin(), [&carry]( char x, char y){
//This starts a lambda function
char z = (x-'0')+(y-'0') + carry; // x,y have ASCII value of each digit
// Substracr ASCII of 0 i.e. 48 to get the "original" number
// Add them up
if (z > 9) //If result greater than 9, you have a carry
{
carry = 1; // store carry for proceeding sums
z -= 10; // Obviously
}
else
{
carry = 0; //Else no carry was generated
}
return z + '0'; // Now you have "correct" number, make it a char, add 48
});
std::transform is present in header <algorithm>, see the ideone posted link.
Here's A Solution for adding two numbers represented as strings .
#include<iostream>
using namespace std;
string add(string a, string b)
{
int al=a.size()-1;
int bl=b.size()-1;
int carry=0;
string result="";
while(al>=0 && bl>=0)
{
int temp = (int)(a[al] - '0') + (int)(b[bl] - '0') + carry ;
carry = 0;
if(temp > 9 )
{
carry=1;
temp=temp-10;
}
result+=char(temp + '0');
al--;
bl--;
}
while(al>=0)
{
int temp = (int)(a[al] - '0') + carry ;
carry = 0;
if(temp>9)
{
carry=1;
temp=temp%10;
}
result+=char(temp + '0');
al--;
}
while(bl>=0)
{
int temp = (int)(b[bl] - '0') + carry ;
carry = 0;
if(temp>9)
{
carry=1;
temp=temp%10;
}
result+=char(temp + '0');
bl--;
}
if(carry)
result+="1";
string addition="";
for(int i=result.size()-1;i>=0;i--)
addition+=result[i]; // reversing the answer
return addition;
}
string trim(string a) // for removing leading 0s
{
string res="";
int i=0;
while(a[i]=='0')
i++;
for(;i<a.size();i++)
res+=a[i];
return res;
}
int main()
{
string a;
string b;
cin>>a>>b;
cout<<trim(add(a,b))<<endl;
}
I am not a very femilier with C++ but cant we do this?
int i = stoi( input1[0]);
int j = stoi( input2[0]);
int x = i+j;
Please note this can be done in C++11 Please refer [1] and 2 as well
You can convert a char to an int by subtracting '0' from it:
char sumdigit = (input1[0]-'0') + (input2[0]-'0') + '0';
atoi() would be a better to go, as far as converting input[0] to an int:
int temp = atoi(input.substr(0,1).c_str());
then use stringstream to convert back to string:
stringstream convert;
convert << temp;
string newString = convert.str();
Here is a solution, but this is so far from sensible that it is not even funny.
GCC 4.7.3: g++ -Wall -Wextra -std=c++0x dumb-big-num.cpp
#include <algorithm>
#include <cctype>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
// dumb big num
// unsigned integer
class DBN {
public:
DBN() : num("0") {}
explicit DBN(const std::string& s) : num(s) {
for (const auto& c : num) {
if (!std::isdigit(c)) { throw std::invalid_argument("DBN::DBN"); } }
std::reverse(std::begin(num), std::end(num)); }
DBN operator+(const DBN& rhs) const {
DBN tmp(*this);
return tmp += rhs; }
DBN& operator+=(const DBN& rhs) {
std::string r;
const int m = std::min(num.size(), rhs.num.size());
int c = 0;
for (int i = 0; i < m; ++i) {
int s = (num[i] - '0') + (rhs.num[i] - '0') + c;
c = s / 10;
s %= 10;
r += static_cast<char>('0' + s); }
const std::string& ref = num.size() < rhs.num.size() ? rhs.num : num;
for (int i = m; i < ref.size(); ++i) {
int s = (ref[i] - '0') + c;
c = s / 10;
s %= 10;
r += static_cast<char>('0' + s); }
if (0 < c) { r += '1'; }
num = r;
return *this; }
friend std::ostream& operator<<(std::ostream& os, const DBN& rhs);
friend std::istream& operator>>(std::istream& os, DBN& rhs);
private:
std::string num;
};
std::ostream& operator<<(std::ostream& os, const DBN& rhs) {
std::string s(rhs.num);
std::reverse(std::begin(s), std::end(s));
return os << s;
}
std::istream& operator>>(std::istream& is, DBN& rhs) {
std::stringstream ss;
char c;
while (is && std::isspace(is.peek())) { is.ignore(); }
while (is) {
if (!std::isdigit(is.peek())) { break; }
is >> c;
ss << c; }
DBN n(ss.str());
rhs = n;
return is;
}
int main() {
DBN a, b, t;
while (std::cin >> a >> b) {
std::cout << a + b << "\n";
(t += a) += b;
}
std::cout << t << "\n";
}
Here it is a simple C++ code
string Sum(string a, string b)
{
if(a.size() < b.size())
swap(a, b);
int j = a.size()-1;
for(int i=b.size()-1; i>=0; i--, j--)
a[j]+=(b[i]-'0');
for(int i=a.size()-1; i>0; i--)
if(a[i] > '9')
{
int d = a[i]-'0';
a[i-1] = ((a[i-1]-'0') + d/10) + '0';
a[i] = (d%10)+'0';
}
if(a[0] > '9')
{
string k;
k+=a[0];
a[0] = ((a[0]-'0')%10)+'0';
k[0] = ((k[0]-'0')/10)+'0';
a = k+a;
}
return a;
}
cited from C - Adding the numbers in 2 strings together if a different length
answer, I write a more readable code:
void str_reverse(char *beg, char *end){
if(!beg || !end)return;
char cTmp;
while(beg < end){
cTmp = *beg;
*beg++ = *end;
*end-- = cTmp;
}
}
#define c2d(c) (c - '0')
#define d2c(d) (d + '0')
void str_add(const char* s1, const char* s2, char* s_ret){
int s1_len = strlen(s1);
int s2_len = strlen(s2);
int max_len = s1_len;
int min_len = s2_len;
const char *ps_max = s1;
const char *ps_min = s2;
if(s2_len > s1_len){
ps_min = s1;min_len = s1_len;
ps_max = s2;max_len = s2_len;
}
int carry = 0;
int i, j = 0;
for (i = max_len - 1; i >= 0; --i) {
// this wrong-prone
int idx = (i - max_len + min_len) >=0 ? (i - max_len + min_len) : -1;
int sum = c2d(ps_max[i]) + (idx >=0 ? c2d(ps_min[idx]) : 0) + carry;
carry = sum / 10;
sum = sum % 10;
s_ret[j++] = d2c(sum);
}
if(carry)s_ret[j] = '1';
str_reverse(s_ret, s_ret + strlen(s_ret) - 1);
}
test code as below:
void test_str_str_add(){
char s1[] = "123";
char s2[] = "456";
char s3[10] = {'\0'};
str_add(s1, s2, s3);
std::cout<<s3<<std::endl;
char s4[] = "456789";
char s5[10] = {'\0'};
str_add(s1, s4, s5);
std::cout<<s5<<std::endl;
char s7[] = "99999";
char s8[] = "21";
char s9[10] = {'\0'};
str_add(s7, s8, s9);
std::cout<<s9<<std::endl;
}
output:
579
456912
100020
I am preparing the interview questions not for homework. There is one question about how to multiple very very long integer. Could anybody offer any source code in C++ to learn from? I am trying to reduce the gap between myself and others by learning other's solution to improve myself.
Thanks so much!
Sorry if you think this is not the right place to ask such questions.
you can use GNU Multiple Precision Arithmetic Library for C++.
If you just want an easy way to multiply huge numbers( Integers ), here you are:
#include<iostream>
#include<string>
#include<sstream>
#define SIZE 700
using namespace std;
class Bignum{
int no[SIZE];
public:
Bignum operator *(Bignum& x){ // overload the * operator
/*
34 x 46
-------
204 // these values are stored in the
136 // two dimensional array mat[][];
-------
1564 // this the value stored in "Bignum ret"
*/
Bignum ret;
int carry=0;
int mat[2*SIZE+1][2*SIZE]={0};
for(int i=SIZE-1;i>=0;i--){
for(int j=SIZE-1;j>=0;j--){
carry += no[i]*x.no[j];
if(carry < 10){
mat[i][j-(SIZE-1-i)]=carry;
carry=0;
}
else{
mat[i][j-(SIZE-1-i)]=carry%10;
carry=carry/10;
}
}
}
for(int i=1;i<SIZE+1;i++){
for(int j=SIZE-1;j>=0;j--){
carry += mat[i][j]+mat[i-1][j];
if(carry < 10){
mat[i][j]=carry;
carry=0;
}
else{
mat[i][j]=carry%10;
carry=carry/10;
}
}
}
for(int i=0;i<SIZE;i++)
ret.no[i]=mat[SIZE][i];
return ret;
}
Bignum (){
for(int i=0;i<SIZE;i++)
no[i]=0;
}
Bignum (string _no){
for(int i=0;i<SIZE;i++)
no[i]=0;
int index=SIZE-1;
for(int i=_no.length()-1;i>=0;i--,index--){
no[index]=_no[i]-'0';
}
}
void print(){
int start=0;
for(int i=0;i<SIZE;i++)
if(no[i]!=0){
start=i;
break; // find the first non zero digit. store the index in start.
}
for(int i=start;i<SIZE;i++) // print the number starting from start till the end of array.
cout<<no[i];
cout<<endl;
return;
}
};
int main(){
Bignum n1("100122354123451234516326245372363523632123458913760187501287519875019671647109857108740138475018937460298374610938765410938457109384571039846");
Bignum n2("92759375839475239085472390845783940752398636109570251809571085701287505712857018570198713984570329867103986475103984765109384675109386713984751098570932847510938247510398475130984571093846571394675137846510874510847513049875610384750183274501978365109387460374651873496710394867103984761098347609138746297561762234873519257610");
Bignum n3 = n1*n2;
n3.print();
return 0;
}
as you can see, it's multiply 2 huge integer :) ... (up to 700 digits)
Try this:
//------------DEVELOPED BY:Ighit F4YSAL-------------
#include<iostream>
#include<string>
#include<sstream>
#define BIG 250 //MAX length input
using namespace std;
int main(){
int DUC[BIG][BIG*2+1]={0},n0[BIG],n1[BIG],i,t,h,carry=0,res;
string _n0,_n1;
while(1){
//-----------------------------------get data------------------------------------------
cout<<"n0=";
cin>>_n0;
cout<<"n1=";
cin>>_n1;
//--------------------string to int[]----------------------------------------
for(i=_n0.length()-1,t=0;i>=0,t<=_n0.length()-1;i--,t++){
n0[i]=_n0[t]-'0';
}
i=0;
for(i=_n1.length()-1,t=0;i>=0,t<=_n1.length()-1;i--,t++){
n1[i]=_n1[t]-'0';
}
i=0;t=0;
//--------------------------produce lines of multiplication----------------
for(i=0;i<=_n1.length()-1;i++){
for(t=0;t<=_n0.length()-1;t++){
res=((n1[i]*n0[t])+carry);
carry=(res/10);
DUC[i][t+i]=res%10;
}
DUC[i][t+i]=carry;
carry=0;
}
i=0;t=0;res=0;carry=0;
//-----------------------------add the lines-------------------------------
for(i=0;i<=_n0.length()*2-1;i++){
for(t=0;t<=_n1.length()-1;t++){
DUC[BIG-1][i]+=DUC[t][i];
//cout<<DUC[t][i]<<"-";
}
res=((DUC[BIG-1][i])+carry);
carry=res/10;
DUC[BIG-1][i]=res%10;
//cout<<" ="<<DUC[BIG-1][i]<<endl;
}
i=0;t=0;
//------------------------print the result------------------------------------
cout<<"n1*n0=";
for(i=_n0.length()*2-1;i>=0;i--){
if((DUC[BIG-1][i]==0) and (t==0)){}else{cout<<DUC[BIG-1][i];t++;}
//cout<<DUC[BIG-1][i];
}
//-------------------------clear all-------------------------------------
for(i=0;i<=BIG-1;i++){
for(t=0;t<=BIG*2;t++){
DUC[i][t]=0;
}
n0[i]=0;n1[i]=0;
}
//--------------------------do it again-------------------------------------
cout<<"\n------------------------------------------------\n\n";
}
return 0;
}
This solution is good for very very big numbers but not so effective for factorial calculation of very big numbers. Hope it will help someone.
#include <iostream>
#include <string>
using namespace std;
string addition(string a, string b) {
string ans = "";
int i, j, temp = 0;
i = a.length() - 1;
j = b.length() - 1;
while (i >= 0 || j >= 0) {
if (i >= 0 && a[i])
temp += a[i] - '0';
if (j >= 0 && b[j])
temp += b[j] - '0';
int t = (temp % 10);
char c = t + '0';
ans = ans + c;
temp = temp / 10;
i--;
j--;
}
while (temp > 0) {
int t = (temp % 10);
char c = t + '0';
ans = ans + c;
temp = temp / 10;
}
string fnal = "";
for (int i = ans.length() - 1;i >= 0;i--) {
fnal = fnal + ans[i];
}
return fnal;
}
string multiplication(string a, string b) {
string a1, b1 = "0";
int i, j, temp = 0, zero = 0;
i = a.length() - 1;
int m1, m2;
while (i >= 0) {
a1 = "";
m1 = a[i] - '0';
j = b.length() - 1;
while (j >= 0) {
m2 = b[j] - '0';
temp = temp + m1*m2;
int t = temp % 10;
char c = t + '0';
a1 = a1 + c;
temp = temp / 10;
j--;
}
while (temp > 0) {
int t = (temp % 10);
char c = t + '0';
a1 = a1 + c;
temp = temp / 10;
}
string fnal = "";
// reverse string
for (int i = a1.length() - 1;i >= 0;i--) {
fnal = fnal + a1[i];
}
a1 = fnal;
//add zero
for (int p = 0;p < zero;p++)
a1 = a1 + '0';
b1 = addition(a1, b1);
i--;
zero++;
}
return b1;
}
// upto 50 is ok
int factorial(int n) {
string a = "1";
for (int i = 2;i <= n;i++) {
string b = to_string(i);
a = multiplication(a, b);
}
cout << a << endl;
return a.length();
}
int main() {
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
int n;
cin >> n;
//cout << factorial(n) << endl;
string a, b;
a = "1281264836465376528195645386412541764536452813416724654125432754276451246124362456354236454857858653";
b = "3767523857619651386274519192362375426426534237624548235729562582916259723586347852943763548355248625";
//addition(a, b);
cout << multiplication(a, b);
return 0;
}