C++陣列中每隔K個素數的乘積
給定一個包含n個素數的陣列arr[n]和k;任務是找到陣列中每隔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個元素遞迴地將其與product變數相乘。
- 列印乘積。
演算法
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
廣告