주어진 n개의 소수와 k를 포함하는 배열 arr[n]; 작업은 배열에 있는 모든 k' 소수의 곱을 찾는 것입니다.
예를 들어 배열 arr[] ={3, 5, 7, 11} 및 k =2이므로 모든 k 즉 5 및 11 뒤에 소수가 있으므로 5x11 =55가 되는 제품을 찾고 결과를 인쇄해야 합니다. 출력으로.
소수란 무엇입니까?
소수는 1 또는 숫자 자체를 제외하고 다른 숫자로 나눌 수 없는 자연수입니다. 소수의 일부는 2, 3, 5, 7, 11, 13 등입니다.
예시
Input: arr[] = {3, 5, 7, 11, 13} k= 2
Output: 55
Explanation: every 2nd element of the array are 5 and 11; their product will be 55
Input: arr[] = {5, 7, 13, 23, 31} k = 3
Output: 13
Explanation: every 3rd element of an array is 13 so the output will be 13. 위 문제를 해결하기 위해 사용할 접근 방식 -
- n개의 요소와 k의 입력 배열을 취하여 모든 k' 요소의 곱을 찾습니다.
- 소수를 저장할 체를 만듭니다.
- 그런 다음 배열을 탐색하고 k' 요소를 가져와 모든 k' 요소에 대해 재귀적으로 곱 변수와 곱해야 합니다.
- 제품을 인쇄합니다.
알고리즘
Start
Step 1-> Define and initialize MAX 1000000
Step 2-> Define bool prime[MAX + 1]
Step 3-> In function createsieve()
Call memset(prime, true, sizeof(prime));
Set prime[1] = false
Set prime[0] = false
Loop For p = 2 and p * p <= MAX and p++
If prime[p] == true then,
For i = p * 2 and i <= MAX and i += p
Set prime[i] = false
Step 4-> void productOfKthPrimes(int arr[], int n, int k)
Set c = 0
Set product = 1
Loop For i = 0 and i < n and i++
If prime[arr[i]] then,
Increment c by 1
If c % k == 0 {
Set product = product * arr[i]
Set c = 0
Print the product
Step 5-> In function main()
Call function createsieve()
Set n = 5, k = 2
Set arr[n] = { 2, 3, 11, 13, 23 }
Call productOfKthPrimes(arr, n, k)
Stop 예시
#include <bits/stdc++.h>
using namespace std;
#define MAX 1000000
bool prime[MAX + 1];
void createsieve() {
memset(prime, true, sizeof(prime));
// 0 and 1 are not prime numbers
prime[1] = false;
prime[0] = false;
for (int p = 2; p * p <= MAX; p++) {
if (prime[p] == true) {
// finding all multiples of p
for (int i = p * 2; i <= MAX; i += p)
prime[i] = false;
}
}
}
// compute the answer
void productOfKthPrimes(int arr[], int n, int k) {
// count the number of primes
int c = 0;
// find the product of the primes
long long int product = 1;
// traverse the array
for (int i = 0; i < n; i++) {
// if the number is a prime
if (prime[arr[i]]) {
c++;
if (c % k == 0) {
product *= arr[i];
c = 0;
}
}
}
cout << product << endl;
}
//main block
int main() {
// create the sieve
createsieve();
int n = 5, k = 2;
int arr[n] = { 2, 3, 11, 13, 23 };
productOfKthPrimes(arr, n, k);
return 0;
} 출력
39