일부 요소가 포함된 정수 배열 arr[]이 주어지면 작업은 해당 숫자의 모든 소수의 곱을 찾는 것입니다.
소수는 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