-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbig-calc.cpp
95 lines (76 loc) · 2.11 KB
/
big-calc.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
string add(string a, string b) {
string output = "";
int carry = 0;
int temp = 0;
int lena = a.length();
int lenb = b.length();
if (lenb > lena) {
swap(a, b);
swap(lena, lenb);
}
for (int i = 0; i < lenb; i++) {
temp = (a[lena - i - 1] - '0') + (b[lenb - i - 1] - '0') + carry;
if (temp >= 10) {
carry = 1;
temp -= 10;
} else {
carry = 0;
}
output.push_back(temp + '0');
}
for (int i = lenb; i < lena; i++) {
temp = (a[lena - i - 1] - '0') + carry;
if (temp >= 10) {
carry = 1;
temp -= 10;
} else {
carry = 0;
}
output.push_back(temp + '0');
}
if (carry) {
output.push_back('1');
}
reverse(output.begin(), output.end());
return output;
}
string multiply(string a, string b) {
int lena = a.length();
int lenb = b.length();
if (a == "0" || b == "0")
return "0"; // نمایش صفر اگر یکی از ارقام صفر بود
vector<int> result(lena + lenb, 0); //ساخت وکتور با حداثر اندازه
// عمل ضرب از اخر به اول
for (int i = lena - 1; i >= 0; i--) {
for (int j = lenb - 1; j >= 0; j--) {
int mul = (a[i] - '0') * (b[j] - '0');
int sum = mul + result[i + j + 1];
result[i + j + 1] = sum % 10;
result[i + j] += sum / 10;
}
}
string output; //خروجی
//برعکس کردن خروجی و برگردادن آن به کاربر
for (int num : result) {
if (!(output.empty() && num == 0)) {
output.push_back(num + '0');
}
}
return output.empty() ? "0" : output;
}
int main() {
string num1 = "";
string num2 = "";
cout << "enter first number : ";
cin >> num1;
cout << "enter second number : ";
cin >> num2;
cout << "\nAnswer: " << multiply(num1, num2) << endl;
system("pause");
return 0;
}