算法題|-查找100以內的孿生素數的組數


所謂孿生素數指的是間隔為2的相鄰素數,就像孿生兄弟。

最小的孿生素數是(3, 5)。

在100 以內的孿生素數還有 (5, 7), (11, 13), (17, 19), (29, 31), (41, 43), (59, 61) 和(71, 73),總計有 8 組。

思路:遍歷到100,先判斷當前的數字是否是素數,是則記錄下來,並且和上一個記錄下來的素數進行比較,如果其差為2,則為一組孿生素數。

 

C#代碼

 1 static int GetPrimeTwins(int number)
 2         {
 3             //素數的個數
 4             int count = 0;
 5             //記錄上一個素數
 6             int lastNum = 0;
 7             for (var i = 2; i <= number; i++)
 8             {
 9                 //默認所有的數字都是素數
10                 bool isSS = true;
11                 for (var j = 2; j <= i / 2; j++)
12                 {
13                     //不是素數,就跳出
14                     if (i % j == 0)
15                     {
16                         isSS = false;
17                         break;
18                     }
19                 }
20                 //如果i是一個素數
21                 if (isSS)
22                 {
23                     //如果上一素數存在
24                     if (lastNum != 0)
25                     {
26                         if (i - lastNum == 2)
27                         {
28                             count++;
29                         }
30                     }
31                     lastNum = i;
32                 }
33             }
34             return count;
35         }

 

Lua代碼

 1 function GetPrimeTwins(number)
 2     local count=0
 3     local lastNum=0
 4     for i=2,number,1 do
 5         isSS=true
 6         for j=2,i/2,1 do
 7             if i%j==0 then
 8                 isSS=false
 9                 break
10             end
11         end
12 
13         if isSS==true then
14             if lastNum~=0 then
15                 if i-lastNum==2 then
16                     count=count+1
17                 end
18             end
19             lastNum=i
20         end
21     end
22     return count
23 end
24 
25 print(GetPrimeTwins(5))     --1
26 print(GetPrimeTwins(7))        --2
27 print(GetPrimeTwins(100))    --8

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM