创建乘积数组,它包含数组中所有元素的乘积,这些元素可以被A[i]整除,而不使用除法运算符

create product Array which contains product of all elements of Array which are divisible by A[i] without using division operator

本文关键字:元素 数组 整除 运算符 除法 包含 创建      更新时间:2023-10-16

给定一个数组并找到乘积数组,其中乘积数组的每个元素计算如下:

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

而不使用除法运算符。

例如A = {2,4,3,7,8}产品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;
}

类似于:

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;
}