创建乘积数组,它包含数组中所有元素的乘积,这些元素可以被A[i]整除,而不使用除法运算符
create product Array which contains product of all elements of Array which are divisible by A[i] without using division operator
给定一个数组并找到乘积数组,其中乘积数组的每个元素计算如下:
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;
}
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用strcpy将char数组的元素复制到另一个数组
- 如何将元素添加到数组的线程安全函数?
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 输出没有重复元素的动态数组(收缩数组)C++
- 数组中最大的非重复元素
- 数组元素打印的递归方法
- 对字符数组中的元素执行逐位操作
- 缓存std::数组的选定元素,并在c++中自动保持其一致性
- 如何计算数组中元素的位数?(不是数组的长度),并计算其数字的总和
- 通过交换元素使数组相同
- 按平均值替换数组中的元素
- 打印矢量数组中的所有元素
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 如何为 c++ 的不同变量类型的结构元素创建动态数组?
- 如何将元素从向量转移到新数组?
- 如何在向量数组中插入元素?
- 为什么 2 个相同数组的元素彼此相等
- C++ 中的二维整数数组,每行中的元素数量不均匀