给定n个整数的数组arr [n],任务是查找数组中所有复合数字的乘积。
合成数是将两个其他整数相乘得到的整数。例如6是一个合成数字,可以通过将2和3分别乘以整数而得到。我们也可以说它们不是素数。
输入值
arr[] = {1, 2, 4, 5, 6, 7}输出结果
24
说明-数组中的复合数字是4和6,它们的乘积是24。
输入值
arr[] = {10, 2, 4, 5, 6, 11}输出结果
240
说明-数组中的复合数字为10、4、6,其乘积为240。
迭代数组的每个元素。
查找非质数或复合数,即可以被除1以外的其他数整除。
将所有复合数字相乘。
返回结果。
Start Step 1→ Declare function to find the product of consecutive numbers in array int product_arr(int arr[], int size) declare int max = *max_element(arr, arr + size) set vector<bool> prime(max + 1, true) set prime[0] = true set prime[1] = true Loop For int i = 2 and i * i <= max and i++ IF (prime[i] == true) Loop For int j = i * 2 and j <= max and j += i Set prime[j] = false End End End Set int product = 1 Loop For int i = 0 and i < size and i++ IF (!prime[arr[i]]) Set product *= arr[i] End End return product Stop
#include <bits/stdc++.h>
using namespace std;
//函数查找数组中连续数字的乘积
int product_arr(int arr[], int size){
int max = *max_element(arr, arr + size);
vector<bool> prime(max + 1, true);
prime[0] = true;
prime[1] = true;
for (int i = 2; i * i <= max; i++){
if (prime[i] == true){
for (int j = i * 2; j <= max; j += i)
prime[j] = false;
}
}
int product = 1;
for (int i = 0; i < size; i++)
if (!prime[arr[i]]){
product *= arr[i];
}
return product;
}
int main(){
int arr[] = { 2, 4, 6, 8, 10};
int size = sizeof(arr) / sizeof(arr[0]);
cout<<"product of consecutive numbers in an array: "<<product_arr(arr, size);
return 0;
}输出结果
如果运行上面的代码,它将生成以下输出-
product of consecutive numbers in an array: 1920