เมื่อกำหนดอาร์เรย์จำนวนเต็ม arr[] กับองค์ประกอบบางอย่าง ภารกิจคือการหาผลคูณของจำนวนเฉพาะทั้งหมดของตัวเลขนั้น
จำนวนเฉพาะคือจำนวนที่หารด้วย 1 หรือจำนวนเฉพาะ หรือจำนวนเฉพาะเป็นตัวเลขที่ตัวเลขอื่นหารด้วย 1 ไม่ได้ ยกเว้น 1 และจำนวนเฉพาะ เช่น 1, 2, 3, 5, 7, 11 เป็นต้น
เราต้องหาวิธีแก้ปัญหาสำหรับอาร์เรย์ที่กำหนด -

ป้อนข้อมูล −arr[] ={ 11, 20, 31, 4, 5, 6, 70 }
ผลผลิต − 1705
คำอธิบาย − จำนวนเฉพาะในอาร์เรย์คือ − 11, 31, 5 ผลคูณคือ 1705
ป้อนข้อมูล − arr[] ={ 1, 2, 3, 4, 5, 6, 7 }
ผลผลิต − 210
คำอธิบาย − จำนวนเฉพาะในอาร์เรย์คือ − 1, 2, 3, 5, 7 ผลคูณคือ 210
แนวทางที่ใช้ด้านล่างมีดังต่อไปนี้ในการแก้ปัญหา
-
รับอินพุตอาร์เรย์ arr[].
-
วนทุกองค์ประกอบและตรวจสอบว่าเป็นจำนวนเฉพาะหรือไม่
-
กำหนดจำนวนเฉพาะปัจจุบันทั้งหมดในอาร์เรย์
-
คืนสินค้า
อัลกอริทึม
Start
In function int prodprimearr(int arr[], int n)
Step 1→ Declare and initialize max_val as max_val *max_element(arr, arr + n)
Step 2→ Declare vector<bool> isprime(max_val + 1, true)
Step 3→ Set isprime[0] and isprime[1] as false
Step 4→ Loop For p = 2 and p * p <= max_val and p++
If isprime[p] == true then,
Loop For i = p * 2 and i <= max_val and i += p
Set isprime[i] as false
Step 5→ Set prod as 1
Step 6→ For i = 0 and i < n and i++
If isprime[arr[i]]
Set prod = prod * arr[i]
Step 6→ Return prod
In function int main(int argc, char const *argv[])
Step 1→ Declare and initilalize arr[] = { 11, 20, 31, 4, 5, 6, 70 }
Step 2→ Declare and initialize n = sizeof(arr) / sizeof(arr[0])
Step 3→ Print the results of prodprimearr(arr, n)
Stop ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
int prodprimearr(int arr[], int n){
// To find the maximum value of an array
int max_val = *max_element(arr, arr + n);
// USE SIEVE TO FIND ALL PRIME NUMBERS LESS
// THAN OR EQUAL TO max_val
vector<bool> isprime(max_val + 1, true);
isprime[0] = false;
isprime[1] = false;
for (int p = 2; p * p <= max_val; p++) {
// If isprime[p] is not changed, then
// it is a prime
if (isprime[p] == true) {
// Update all multiples of p
for (int i = p * 2; i <= max_val; i += p)
isprime[i] = false;
}
}
// Product all primes in arr[]
int prod = 1;
for (int i = 0; i < n; i++)
if (isprime[arr[i]])
prod *= arr[i];
return prod;
}
int main(int argc, char const *argv[]){
int arr[] = { 11, 20, 31, 4, 5, 6, 70 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << prodprimearr(arr, n);
return 0;
} ผลลัพธ์
หากรันโค้ดด้านบน มันจะสร้างผลลัพธ์ต่อไปนี้ -
1705