C 不使用*运算符的乘法

C 不使用*运算符的乘法,c,C,我正在尝试一个代码,它将两个数字相乘,并且不应该使用*运算符。我写了这段代码,但没有给出预期的解决方案 #include<stdio.h> #include<stdlib.h> int main(int ar,char *arg[]) { long int a; long int b; sscanf(arg[1],"%ld",&a); sscanf(arg[2],"%ld",&b); long int count=0;

我正在尝试一个代码,它将两个数字相乘,并且不应该使用*运算符。我写了这段代码,但没有给出预期的解决方案

#include<stdio.h>
#include<stdlib.h>

int main(int ar,char *arg[])
{
   long int a;
   long int b;

   sscanf(arg[1],"%ld",&a);
   sscanf(arg[2],"%ld",&b);

   long int count=0;
   long int temp=b;
   long int prod=0;

   while(temp>0)
   {
       count=0;

       while(temp/2>0)
       {
          temp/=2;
          count++;
       }

       prod+=a<<(count);
       temp=b-(1<<count);
   }

   //printf("%ld %d\n",count,1<<count);
   printf("%ld\n",prod);
   return 0;
}
#包括
#包括
int main(int-ar,char*arg[]
{
长INTA;
长int b;
sscanf(arg[1]、“%ld”、&a);
sscanf(arg[2]、“%ld”、&b);
长整数计数=0;
长整数温度=b;
长int prod=0;
而(温度>0)
{
计数=0;
而(温度/2>0)
{
温度/=2;
计数++;
}

prod+=a以这种方式编辑while循环

while(temp>0)
{
    count=0;
    while(temp/2>0)
    {
        temp/=2;
        count++;
    }
    prod+=a<<(count);
    temp=b-(1<<count);
    b=temp  //<--
}
while(温度>0)
{
计数=0;
而(温度/2>0)
{
温度/=2;
计数++;
}

Pid++a

而ViayaWSM给出了解决方案。我认为你可能会考虑从LSB上去解决它。

   while(b>0)
   {
       if (b % 2 == 1)
          prod+=a;

       a=a<<1;
       b=b>>1;
   }
while(b>0)
{
如果(b%2==1)
prod+=a;
a=a1;
}
类乘法
{
公共静态void main(字符串[]args)
{
int a,b,值=0;
a=7;
b=4;

对于(inti=1;我等不及了。)下次请自己做。提示:你的代码可能会对输入工作,比如
2^n
。它不是很复杂吗?我的意思是3*2它只是3+3=>对于(inti=0;它肯定有O(我的上帝)的渐近行为。
   class Multiply
       {
             public static void main(String [] args)
              {
                   int a,b,value=0;
                   a=7;
                   b=4;
                   for(int i=1;i<=b;i++){
                   value+=a;
              }
             System.out.println("Multiplication is:\t" + value);
        }