Problems with prime numbers

A more common judgment method

bool IsPrime()
{
    
    
	for(int i=2;i<=sqrt(n);i++)
	{
    
    
		if(n%2==0)
			return false;
	}
	return true;
}

Eratosthenes screening method (multiples of prime numbers must not be prime numbers)
At the same time, for each x, the multiple of x greater than or equal to the square of x is marked as a composite number.

void primes(int n)
{
    
    
	memset(v,0,sizeof(v));
	for(i=2;i<=n;i++)
	{
    
    
		if(v[i]) continue;
		cout<<i<<endl;
		for(j=i;j<=n/i;j++)
			v[i][j]=1;
	}
}

Linear sieve method
Each composite number will only be sifted by its smallest prime factor once, and the time complexity is O(n)

int v[maxn],prime[maxn];
void primes(int n)
{
    
    
	memset(v,0,sizeof(v));///最小质因子
	m=0;
	for(i=2;i<=n;i++)
	{
    
    
		if(v[i]==0)///i为质数
		{
    
    
			v[i]=i;
			prime[++m]=i;
		}
		///给当前的数i乘上一个质因子
		for(j=1;j<=m;j++)
		{
    
    
			///i有比prime[i]更小的质因子,或者超出n的范围
			if(prime[j]>v[i]||prime[j]>n/i) break;
			v[i*prime[j]]=prime[j];
		}
	}
	for(i=1;i<=m;i++)
		cout<<prime[i]<<endl;
}

There is also a method for judging prime numbers that I saw on the Internet. This was a template that was also used by ccpc at that time.

bool isPrime( int num )
{
    
    
	//两个较小数另外处理
    if(num ==2|| num==3 )
        return 1 ;
    //不在6的倍数两侧的一定不是质数
        if(num %6!= 1&&num %6!= 5)
             return 0 ;
        int tmp =sqrt( num);
           //在6的倍数两侧的也可能不是质数
        for(int i= 5;i <=tmp; i+=6 )
             if(num %i== 0||num %(i+ 2)==0 )
                   return 0 ;
        //排除所有,剩余的是质数
        return 1 ;
}

This is the fastest way I have seen to judge prime numbers

Guess you like

Origin blog.csdn.net/weixin_46434074/article/details/108826261