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