首页 文章

create product Array包含Array的所有元素的乘积,可以在不使用除法运算符的情况下被A [i]整除

提问于
浏览
0

给定一个数组并查找产品数组,其中Product Array的每个元素的计算方法如下:

B[i] = product of all the element of A which are divisible by A[i]

不使用除法运算符 .

例如 A = {2,4,3,7,8} product Array = {32,8,0,0,0}

我尝试使用O(n2)方法求解 . 对于每个数字,我搜索数组并检查它是否可被给定数字整除或不使用(减法运算我执行除法)然后乘以所有这些数字 .

bool division(int x,int y){
  while(x>=y){
    x=x-y;
  }  
  if(x!=0)
    return false;
  else
    return true;
}

int main()
{

  int n=5;
  int A[]={2,4,3,7,8};
  int prod[5];
  int mul=1;
  for(int i=0;i<n;i++){
    mul=1;
    for(int j=0;j<n;j++) 
    {
      if(i!=j)
      {
         bool isdivisible=division(A[j],A[i]); 
         if(isdivisible==1)
         {
            mul=mul*A[j];
         }
      }
    }
    if(mul!=1)
      prod[i]=mul;
    else
      prod[i]=0;
  }
  for(int k=0;k<n;k++)
    cout<<prod[k]<<endl;
  return 0;
}

1 回答

  • 0

    就像是:

    std::vector<int> do_stuff(const std::vector<int>& a)
    {
        std::vector<int> out(a.size(), 0);
        const int len = a.size();
    
        for (int i=0; i<len; i++)
        {
            out[i] = 1;
    
            for (int k=0; k<len; k++)
                if (i != k && a[k] % a[i] == 0)
                    out[i] *= a[k];
        }
    
        return out;
    }
    

相关问题