【问题标题】:Write a program that multiplies together two number without using arithemetic operators [duplicate]编写一个不使用算术运算符将两个数字相乘的程序[重复]
【发布时间】:2011-01-21 06:41:31
【问题描述】:

可能重复:
How to add two numbers without using ++ or + or another arithmetic operator.

是否可以在不使用任何算术运算符(*、+、-、/、%)的情况下编写一个程序(用 C 语言)将两个数字相乘。

【问题讨论】:

  • 重复:stackoverflow.com/questions/1149929/… 虽然答案非常壮观
  • @SiegeX:“如何将两个数相乘”这个问题如何? “如何添加两个数字”的副本。引用问题中给出的答案也回答了这个问题,但这不会使问题重复。

标签: c


【解决方案1】:

如果您可以使用按位运算符进行加法,下面的代码 sn-p 可能会有所帮助

int xor, and, temp;
and = x & y;
xor = x ^ y; 

while(and != 0 )
{
 and <<= 1; 
 temp = xor ^ and;
 and &= xor; 
 xor = temp; 
}

a 和 b 相乘加“a”“b”次

unsigned int mult(unsigned int a,unsigned int b)
{
    unsigned int counter=0;
    unsigned int mult = a;
    if(a == 0 || b == 0)
    {
    return 0;
    }

    //Optimize if any of the number is power of two then
    //Just right shift other with value of this number

    while(counter < b )
    {   
    counter = add(counter,1);
    mult = add(mult,a);
    }
    return mult;
}

【讨论】:

  • 结果在哪里?是异或吗?如果是这样,它看起来像 2 * 1 = 3
  • 实际上将它与我的解决方案结合起来是可行的。您可以将其中一个数字分解为 2 的幂,然后将第二个乘以每个,然后将所有结果相加
【解决方案2】:

当然——如果图灵机可以做到,C 也可以(只要你有足够的内存)。但你可能不会看到我写它。

如果您想自己执行此操作,一种方法是模拟您如何在纸上将两个数字相乘。您象征性地使用数字。您只需要处理每个数字和一个用于乘以这些数字的结果表。

对于两个数字相加,可以使用类似的“加法”表。

你使用的数字是十进制数字还是二进制数字都没有关系 - 原理是一样的。

【讨论】:

    【解决方案3】:

    以下是使用农民算法的方法。 add() 来自 Neera 在我面前给出的答案:

    #include <stdio.h>
    
    unsigned int add(unsigned int x, unsigned int y)
    {
            unsigned int xor, and, temp;
            and = x & y;
            xor = x ^ y;
            while(and != 0 ) {
                    and <<= 1;
                    temp = xor ^ and;
                    and &= xor;
                    xor = temp;
            }
            return xor;
    }
    
    int main()
    {
            unsigned int multiplicand = 41,
                         multiplier = 6,
                         res = 0;
    
            while(multiplier != 0) {
                    if (multiplier & 1) {
                            res = add(res, multiplicand);
                    }
                    multiplier >>= 1;
                    multiplicand <<= 1;
            }
            printf("6 times 41 equals %u\n", res);
            return 0;
    }
    

    【讨论】:

      【解决方案4】:

      您可以使用图灵机将两个数字相乘,可以说它不使用任何算术运算符,只需向左/向右移动磁带,在磁带上添加/删除标记。因此,您可以编写一个模拟图灵乘数的 C 程序。

      【讨论】:

        【解决方案5】:

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-09-08
          • 1970-01-01
          • 2011-05-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-08-16
          相关资源
          最近更新 更多