分治 大整數乘法

2021-07-28 07:45:19 字數 1517 閱讀 7292

第一次自己完整寫對,多多指教

演算法思路:分治。

第一步:經過預處理將兩個整數變為長度一樣的兩個數(短的在前面補0)

第二部:把兩個大整數都平分為前後兩部分

第三部:按以下公式計算

(實現大數乘法之前實現了大數加減法)

公式:

x=a*10^(n/2)+b

y=c*10^(n/2)+d

xy=ac*10^n+((a-b)(d-c)+ac+bd)*10^(n/2)+bd

#include#include#include#includeusing namespace std;

class bigintegercalculate

} static void wipeofffzero(string& numb)

static void mulinit(string& numb1, string& numb2)

for (int i = 0; i= 0 && j >= 0; --i, --j)

for (; i >= 0; --i)

for (; j >= 0; --j)

if (up != 0) result.push_back(up + '0');

reverse(result.begin(), result.end());

return result;

} static string sub(string numb1, string numb2)

if (numb2[0] == '-')

string result = "";

int sign = 1;

int len1 = numb1.length();

int len2 = numb2.length();

string left = numb1, right = numb2;

if (len1= 0 && j >= 0; --i, --j) ;

result.push_back(t + '0');

} for (; i >= 0; --i) ;

result.push_back(t + '0');

} for (; j >= 0; --j) ;

result.push_back(t + '0');

} reverse(result.begin(), result.end());

if (sign == -1)

result = '-' + result;

wipeofffzero(result);

return result;

} static void tzerro(string& numb)

分治 大整數乘法

問題描述 設x和y是兩個n位的二進位制整數,現在要計算它們的乘積xy,傳統方法計算每2個1位數乘法或加法都看作一步運算,這樣需要o n2 次位運算,代價太高,現在運用分治法設計乙個更有效的大整數乘法演算法。當n 1時,計算x y就是一次位乘。現在對x y進行劃分,把x和y各分為兩段,每段長為n 2 ...

分治演算法 大整數乘法

用分治演算法程式設計實現兩個n 位十進位製大整數的乘法運算。分析 用分治演算法程式設計實現兩個n 位十進位製大整數的乘法運算。演算法描述 兩個十進位制的數 x y x a 10 n1 b y c 10 n2 d 則 x y a 10 n1 b c 10 n2 d 設乙個陣列,將其看做10000 進製...

分治遞迴 大整數乘法

設x,y十進位制整數,計算乘積xy。用小學方法設計演算法,計算步驟太多,而且效率低。t n o n 2 所以用分治方法設計更有效的大整數乘法。將n為十進位制整數x,y分為兩段,每段長為n 2 若位數為奇數,每段長為 n 2 n 2 1 x分為a和b,y分為c和d.比如 8945456 即a 89,b...