單鏈表實現Eratosthenes篩選法

2021-09-03 02:39:19 字數 735 閱讀 1352

對於任意正整數n,eratosthenes篩法可表示如下:

第1步,找出小於等於√n的全部素數:p1、p2、p3、…pm。

第2步,在1~n中分別劃去p1、p2、…pm全部倍數(除了他們自己本身)。

第2步完成後剩下的整數除1外就是不超過n的全部素數。

簡而言之,篩選原理如下:對於乙個正整數a<=n,如果素數p1、p2、…、pm(小於等於√n)都不整除a,則a是素數。

下面是c++的單鏈表實現:

#include #includeusing namespace std;

const int n(20);//設定所能求的最大數,這裡為400

struct node

;class eratosthenes

;eratosthenes::eratosthenes(int n)

}void eratosthenes::delete(node *t)

void eratosthenes::sqrtn()

}void eratosthenes::de()

else

} }}

int eratosthenes::factorial(int n)//遞迴函式求階乘

void eratosthenes::print()

//控制輸出格式

q = q->next;

t++; }}

int main()

單鏈表實現

單鏈表 1 邏輯上連續,位置上可以不連續的儲存方式。2 單鏈表由無數個結點組成,每個結點由資料段和指標域組成,資料段儲存資料,指標域儲存後繼的位址。3 每個結點最多有乙個前繼和乙個後繼。4 其中第乙個結點沒有前繼,所以我們通常建立乙個頭結點來儲存他的位置,其中頭結點的資料段我們不關注。5 最後乙個結...

單鏈表實現

include include define max 50 struct lnode 求鍊錶的長度 不包含頭結點 int length struct lnode node return i 初始化頭 int inithead struct lnode p struct lnode insert st...

單鏈表的實現

include includetypedef struct node 定義鍊錶 snode snode creat 建立鍊錶的函式 q next null return head int length snode head 測鍊錶的結點數 return i void display snode he...