C++單鏈表中所有素數節點的乘積


給定n個節點,任務是列印單鏈表中所有素數節點的乘積。素數節點是指其計數位置的值為素數的節點。

輸入

10 20 30 40 50

輸出

4,00,000

解釋 − 10位於索引值1處,它不是素數,因此將跳過它。移動到索引值為2的20,這是一個素數,因此將被考慮在內。同樣,40和50位於素數索引位置。

乘積 − 20*40*50 = 4,00,000

在上圖中,紅色節點表示素數節點

下面使用的方案如下

  • 取一個臨時指標,例如型別為node的temp

  • 將此temp指標設定為head指標指向的第一個節點

  • 將temp移動到temp→next並檢查該節點是素數節點還是非素數節點。如果節點是素數節點

  • 執行 設定 product=product*(temp→data)

  • 如果節點不是素數,則移動到下一個節點

  • 列印product變數的最終值。

演算法

Start
Step 1 → create structure of a node to insert into a list
   struct node
      int data;
      node* next
   End
Step 2 → declare function to insert a node in a list
   void push(node** head_ref, int data)
      Set node* newnode = (node*)malloc(sizeof(struct node))
      Set newnode→data = data
      Set newnode→next = (*head_ref)
      Set (*head_ref) = newnode
   End
Step 3 → Declare a function to check for prime or not
   bool isPrime(int data)
      IF data <= 1
         return false
      End
      IF data <= 3
         return true
      End
      IF data % 2 = 0 || data % 3 = 0
         return false
      Loop For int i = 5 and i * i <= data and i = i + 6
         IFdata % i = 0 || data % (i + 2) = 0
            return false
         End
      End
      return true
Step 4→ declare a function to calculate product
   void product(node* head_ref)
      set int product = 1
      set node* ptr = head_ref
      While ptr != NULL
         IF (isPrime(ptr→data))
            Set product *= ptr→data
         End
         Set ptr = ptr→next
      End
      Print product
Step 5 → In main()
   Declare node* head = NULL
   Call push(&head, 10)
   Call push(&head, 2)
   Call product(head)
Stop

示例

線上演示

#include <bits/stdc++.h>
using namespace std;
//structure of a node
struct node{
   int data;
   node* next;
};
//function to insert a node
void push(node** head_ref, int data){
   node* newnode = (node*)malloc(sizeof(struct node));
   newnode→data = data;
   newnode→next = (*head_ref);
   (*head_ref) = newnode;
}
// Function to check if a number is prime
bool isPrime(int data){
   if (data <= 1)
      return false;
   if (data <= 3)
      return true;
   if (data % 2 == 0 || data % 3 == 0)
      return false;
   for (int i = 5; i * i <= data; i = i + 6)
      if (data % i == 0 || data % (i + 2) == 0)
         return false;
   return true;
}
//function to find the product
void product(node* head_ref){
   int product = 1;
   node* ptr = head_ref;
   while (ptr != NULL){
      if (isPrime(ptr→data)){
         product *= ptr→data;
      }
      ptr = ptr→next;
   }
   cout << "Product of all the prime nodes of a linked list = " << product;
}
int main(){
   node* head = NULL;
   push(&head, 10);
   push(&head, 2);
   push(&head, 7);
   push(&head, 6);
   push(&head, 85);
   product(head);
   return 0;
}

輸出

如果執行上述程式碼,它將生成以下輸出:

Product of all the prime nodes of a linked list = 14

更新於:2020年8月13日

229 次檢視

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.