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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP