In recent days, the brain more and more stupid, a simple prime circle problem tangled day, did not understand the idea of backtracking, but involving the prime words, suddenly want to summarize the commonly used prime number to hit the table,
In general, the following code is used:
#include <math.h>//primes # include <stdio.h> #include <string.h> #include <algorithm> #include <iostream>using namespace std; #define MAXN 1000000bool P1[MAXN]; Determine if I in p[i] is a prime number int P2[MAXN]; Storage prime number void Prim_num () { int i,j,n; for (I=1; i<=maxn; i++) p1[i]=true; n= (int) sqrt (MAXN); for (i=2; i<=n; i++) { for (j=i+i; j<=maxn; j+=i) //prime is not a prime number, which is to determine which numbers are not primes { p1[j]= false; } } J=1; for (I=1; i<=maxn; i++) //The prime number is stored in pmaxn[n], the following table starts from 1 { if (P1[i]) { p2[j++]=i; }} } int main () { int i; Prim_num (); for (i=1;i<=100;i++)//outputs the first 100 primes { printf ("%d", P2[i]); } return 0;}
From the Internet to find another way of writing, efficiency significantly improved a lot, linear sieve method, is still in the deep ...
The code is as follows:
/* Number of prime numbers to be estimated when encountering primes: num = N/lnx;num is approximate, and the larger the error is the smaller (only estimates are used to estimate the array size of prime tables) Linear Sieve method wwwww*/#include <iostream> #include <cstring> #include <cstdio> #include <cmath> #include <algorithm>using namespace std; #define MAXN 10010000int n;bool visit[maxn];int prime[maxn];void isprime () {memset (visit, True, sizeof (visit)); int num = 0; for (int i = 2; I <= n; ++i) {if (visit[i] = = true) {num++; Prime[num] = i; } for (int j = 1; ((J <= num) && (i * prime[j] <= n)); ++J) {Visit[i * Prime[j]] = false; if (i% prime[j] = = 0) break; Dig into the place! }}}int Main () {memset (prime, 0, sizeof (prime)); int count= 0; scanf ("%d", &n); IsPrime (); for (int i = 0; I <= n; ++i) if (Prime[i]) {printf ("%d", prime[i]); count++; } printf ("\ n"); printf ("The sum of prime num is:%d\n", count); return 0;}In the future to use the prime number, the direct copy, convenient many
General Prime number playing table + efficient algorithm