เมื่อกำหนดอาร์เรย์ arr[n] ของจำนวน n จำนวนเต็ม ภารกิจคือค้นหาผลคูณของตัวเลขประกอบทั้งหมดในอาร์เรย์
จำนวนเชิงประกอบคือจำนวนเต็มที่เกิดจากการคูณจำนวนเต็มอีก 2 จำนวน ตัวอย่างเช่น 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