C++ 中单向链表中最小和最大质数。


问题陈述

给定一个包含 n 个正整数的链表。我们需要找出最小值和最大值质数。

如果给定链表为 -

10 -> 4 -> 1 -> 12 -> 13 -> 7 -> 6 -> 2 -> 27 -> 33
then minimum prime number is 2 and maximum prime number is 13

算法

1. Find maximum number from given number. Let us call it maxNumber
2. Generate prime numbers from 1 to maxNumber and store them in a dynamic array
3. Iterate linked list and use dynamic array to find prime number with minimum and maximum value

示例

#include <iostream>
#include <vector>
#include <climits>
#include <algorithm>
#include <list>
#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
using namespace std;
void printMinAndMaxPrimes(list<int> intList){
   int maxNumber = *max_element(intList.begin(),
   intList.end());
   vector<bool> primes(maxNumber + 1, true);
   primes[0] = primes[1] = false;
   for (int p = 2; p * p <= maxNumber; ++p) {
      if (primes[p]) {
         for (int i = p * 2; i <= maxNumber; i +=p) {
            primes[i] = false;
         }
      }
   }
   int minPrime = INT_MAX;
   int maxPrime = INT_MIN;
   for (auto it = intList.begin(); it != intList.end(); ++it) {
      if (primes[*it]) {
         minPrime = min(minPrime, *it);
         maxPrime = max(maxPrime, *it);
      }
   }
   cout << "Prime number of min value = " << minPrime << "\n";
   cout << "Prime number of max value = " << maxPrime << "\n";
}
int main(){
   int arr [] = {10, 4, 1, 12, 13, 7, 6, 2, 27, 33};
   list<int> intList(arr, arr + SIZE(arr));
   printMinAndMaxPrimes(intList);
   return 0;
}

输出

编译并执行以上程序后,将生成以下输出 -

Prime number of min value = 2
Prime number of max value = 13

更新于: 2019 年 9 月 23 日

129 次浏览

开启您的职业生涯

完成课程,获得认证

开始
广告