題目
俄式乘法,又被稱爲俄國農夫法,它是對兩個正整數相乘的非主流算法。假設m和n是兩個正整數,我們要計算它們的積。它的主要原理如下: if n is 偶數 n m=n/2 2m else n * m=(n-1)/2 + m 該算法只包括折半,加倍,相加等幾個簡單操作,因此實現速度非常快。具體計算如下圖所示:
輸入
兩個正整數 n,m。
輸出
n和m的乘積。
輸出整個求和表達式,運算符與數字之間用一個空格隔開。
樣例輸入
50 65
樣例輸出
130 + 1040 + 2080 = 3250
源代碼
#include <iostream>
using namespace std;
int calculate(int n, int m) {
int s = 0;
while (n != 1) {
if (n % 2 != 0) {
cout << m << " " << "+" << " ";
s += m;
}
n = n / 2;
m = 2 * m;
}
s += m;
cout << m << " " << "=" << " " << s << endl;
return 0;
}
int main() {
int n, m;
cin >> n >> m;
calculate(n, m);
return 0;
}