将乘法算法从伪代码转换为C

时间:2017-03-12 23:22:49

标签: c algorithm pseudocode

我认为我没有正确地将以下伪代码转换为C:

multiply(a[1..p], b[1..q], base)                           // Operands containing rightmost digits at index 1                         
product = [1..p+q]                                         //Allocate space for result                 
for b_i = 1 to q                                           // for all digits in b                                   
  carry = 0
  for a_i = 1 to p                                        //for all digits in a                               
    product[a_i + b_i - 1] += carry + a[a_i] * b[b_i]
    carry = product[a_i + b_i - 1] / base
    product[a_i + b_i - 1] = product[a_i + b_i - 1] mod base
  product[b_i + p] += carry                              // last digit comes from final carry               
return product

该伪代码包含“长乘法”(学校教授的乘法方法)所需的算法,我试图将其转换为C,但没有将其转换为函数并且确实使用了一些测试值[ 1..p]和b [1..q]。

C代码:

 int a [2] = { 0, 3 };
 int b [2] = { 0, 2 };

 int product [4];

 int b_i;
 int a_i;
 int product_i;

 for ( b_i = 0; b_i < 2; b_i++) {
    int carry = 0;
    for ( a_i = 0; a_i < 2; a_i++) {
            product[a_i + b_i - 1] += carry + ( a[a_i] * b[b_i] );
            carry = product [a_i + b_i - 1] / 10;
            product[ a_i + b_i - 1] = product[a_i + b_i -1] % 10;
    }
    product[b_i + 2] += carry;
 }
for (product_i = 0; product_i < 4; product_i++ ) {
    printf("%d", product[product_i] );
}

选择的数字(30和20)显示正确的答案,但它并不适用于所有数字。

1 个答案:

答案 0 :(得分:0)

这有效:

 int product [4] = {0, 0, 0, 0};
for ( b_i = 2; b_i > 0; b_i--) {
int carry = 0;
for ( a_i = 2; a_i > 0; a_i--) {
        product[a_i + b_i - 1] += carry + ( a[a_i-1] * b[b_i-1] );
        carry = product [a_i + b_i - 1] / 10;
        product[ a_i + b_i - 1] = product[a_i + b_i -1] % 10;
   }
product[b_i - 1] += carry;
}

这避免指向[0]和b [0]