The method of seeking a plurality of prime numbers

Sieve method defined
principle : by definition come to prime.
It can not be divisible by a prime number

bool isprime(int n)//是则返回真,不是则为假 
{
	int i=2;//1因为我们人为定义它不是素数,而且1也会陷入死循环 
	while (i<=sqrt(n)&&n%i!=0) ++i;//当它不超过n的平方根时,用n一个一个试; 
	if(i<=sqrt(n))return 0;//没经受住上述历练 
	else return 1;//通关 
}

Erichsen sieve method
did not talk much to say, on the code:

int slove(int n)
{
    int p=0;//用来记录素数的多少 
    for(int i=0;i<=n;i++)
        is_prime[i]=true;//先把它初始化
    is_prime[0]=is_prime[1]=false;//人为规定0,1不是素数 
    for(int i=2;i<=n;i++)//枚举 
    {
        if(is_prime[i])//如果它是素数
        {
            prime[p++]=i;//计算素数的个数,也记录下了素数
            for(int j=2*i;j<=n;j+=i)//用它去筛它的素数 
                is_prime[j]=false;//它的倍数自然不是质数 
        }
    }
    return p;//返回多少个素数 
}

European screening method
Euler function and Euler method for finding prime numbers seeking sieve method is very sophisticated algorithms.

Euler number is a function of the number of positive integers less than n coprime with n, European sieve is revolves around the Euler function.

Principle: Euler function body, derived operating European sieve

We also need to know characteristics:
1. If a is a prime number, Phi [a] = a-. 1;
2. If a is a prime number, B MOD a = 0, Phi [a * B] = Phi [B] a
. 3. If a, b coprime, Phi [a
B] = Phi [a] Phi [B] (when A is a prime number, IF B MOD a! = 0, Phi [a B] = Phi [a] * Phi [B ])

#include <stdio.h>
#include <iostream>
#include <cmath>
#include <string.h>
using namespace std;
bool f[1000005];
int main()
{
  int n;
  scanf("%d",&n);
  f[1]=false;
  for(int i=2;i<=n;i++)
  f[i]=true;
  for(int i=2;i<=n;i++)
  {
    if(f[i]==true)
    {
      for(int j=2;j*i<=n;j++)
      f[i*j]=false;
    }
  }
  for(int i=2;i<=n;i++)
  if(f[i])
  printf("%d ",i);
}

Guess you like

Origin blog.csdn.net/qq_43090158/article/details/94716037