高精度演算-配列シミュレーションを使用

3435 ワード

大きな整数は高精度演算を行い,一つの基礎的な方法は配列を開いて演算シミュレーションを行うことである.
高精度加算:
#include
#include
using namespace std;
string s1, s2;
longlong a[100000], b[100000], c[100000];
int main()
{
	cin >> s1 >> s2;
long long lena = s1.size(), lenb = s2.size();
for (long long i = 0; i < lena; i++) //           ,           
  a[lena - i] = s1[i]-'0';
for (long long i = 0; i < lenb; i++)
  b[lenb - i] = s2[i]-'0';
int lenc = 1, x=0;
  while (lenc <= lena || lenc <= lenb)
  {
   c[lenc] = a[lenc] + b[lenc] + x; //          
   x = c[lenc] / 10;
   c[lenc] %= 10;
   lenc++;
  }
c[lenc] = x;
if (c[lenc] == 0) //     
 lenc--;
for (long long i = lenc; i >= 1; i--) 
 cout << c[i];
return 0;
}

 
高精度減算:#include #include #include using namespace std; string s1, s2; long long a[100000], b[100000], c[100000], flag = 0; int main() { cin >> s1 >> s2; long long lena = s1.size(), lenb = s2.size(); if (lena < lenb || (lena == lenb&&s1 < s2)) // { swap(lena, lenb); string tmp; tmp = s1, s1 = s2, s2 = tmp; flag = 1; } for (long long i = 0; i < lena; i++) a[lena - i] = s1[i]-'0'; for (long long i = 0; i < lenb; i++) b[lenb - i] = s2[i]-'0'; int lenc = 1; while (lenc <= lena || lenc <= lenb) { if (a[lenc] < b[lenc]) // { a[lenc + 1]--; a[lenc] += 10; } c[lenc] = a[lenc] - b[lenc]; lenc++; } lenc--; if (c[lenc] == 0) // lenc--; if (s1 != s2) { if (flag) cout << '-'; for (long long i = lenc; i >= 1; i--) cout << c[i]; } else cout << '0' << endl; return 0; }高精度乗算:#include #include using namespace std; string s1, s2; long long a[100000], b[100000], c[100000]; int main() { cin >> s1 >> s2; long long lena = s1.size(), lenb = s2.size(); for (long long i = 0; i < lena; i++) a[lena - i] = s1[i]-'0'; for (long long i = 0; i < lenb; i++) b[lenb - i] = s2[i]-'0'; for (long long i = 1; i <= lena; i++) { for (long long j = 1; j <= lenb; j++) // c[i + j - 1] += a[i] * b[j]; } for (long long i = 1; i <= lena + lenb-1; i++) { if (c[i] >= 10) // { c[i + 1] += c[i] / 10; c[i] %= 10; } } if(c[lena+lenb]==0) // for (long long i =lena+lenb-1; i >= 1; i--) cout << c[i]; else for (long long i = lena + lenb; i >= 1; i--) cout << c[i]; return 0; }//乗算コア逐位サイクル乗算
c[i + j - 1] += a[i] * b[j];
}
for (long long i = 1; i <= lena + lenb-1; i++)
{
if(c[i]>=10)/キャリー操作
{
c[i + 1] += c[i]/10;
c[i] %= 10;
}
}
if(c[lena+lenb]==0)/最高位検出
for (long long i =lena+lenb-1; i >= 1; i--)
cout << c[i];
else
for (long long i = lena + lenb; i >= 1; i--)
cout << c[i];
return 0;
}