算法题|-查找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

 

posted @ 2019-01-14 16:54  qwert13771  阅读(3064)  评论(0编辑  收藏  举报