C++ 中数组中所有合数的乘积
给定一个包含 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;
//function to find product of consecutive numbers in an array
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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP