道可道,非常道

无名者,圣人也
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

[原创]判断质数的改进算法

Posted on 2008-03-19 14:53  一岩一道  阅读(660)  评论(0编辑  收藏  举报
参考了redraiment的 求质数的方法
转载请注明出处
基本原理:判断N是否为质数,给定一个初始化数组p[]={2,3,5},总数total=3.
若N<=p[total]*p[total],从p中找N的因子,如果找不到,则N为质数。
若N>p[total]*p[total], 首先从p中找N的因子,如果找不到。扩展N直到N<=p[total]*p[total],扩展的同时,计算新增的质数p[total]是否为N的因子。

代码如下:
        public bool IsPrime(long[] prime, long n, ref int total)
        
{
            
if (n == 1)
                
return false;
            
long i, j;
            
long gab = 2//6n+1, 6n+5.for example: 7 11 13 17 (4,2,4,2)
            bool flag;
            i 
= n;
            
for (j = 0; prime[j] * prime[j] <= i; j++)
            
{
                
if (j > total - 1)
                
{
                    
break;
                }

                
if(i % prime[j] == 0)
                
{
                    
//Console.WriteLine(n+"  Number:" + prime[j]);
                    return false;
                }

            }

            
if (n > prime[total] * prime[total - 1])
            
{//产生更长的素数表
                
//reset gab,for example: 7 11 13. 7%6=1
                i = prime[total - 1];
                
if (prime[total - 1% 6 > 1)
                    gab 
= 2;
                
else
                    gab 
= 4;

                
while (n > prime[total - 1* prime[total - 1])
                
{
                    flag 
= true;
                    i 
= i + gab;
                    gab 
= 6 - gab;
                    
for (j = 0; prime[j] * prime[j] <= i; j++)
                    
{
                        
if (i % prime[j] == 0)
                        
{
                            flag 
= false;
                            
break;
                        }

                    }

                    
if (flag)
                    
{
                        prime[total] 
= i;
                        total
++;
                    }

                    
if (n % prime[total - 1== 0)
                    
{
                        
//Console.WriteLine("Number:" + prime[total - 1]);
                        return false;
                    }

                }

            }

            
return true;
        }