"ACM Newsletter"
One chapter at a time, read carefully
ANSI American National Standards Institute American Standards Society
1.1 Calculating prime numbers
#include <stdio.h>intPrimeintN) { inti; for(i =2; i<n;i++) {999if(n%i==0) 78022return 0; 831return 1; 168}}main () {intI, N; N= +; 1 for(i=2; i<=n;i++) 1 {if(Prime (i)) 999 {printf ("%d", i); 168} }}
Prime concept:
1. In all integers larger than 1, except 1 and itself, there are no more approximations, such integers are called prime numbers or primes. It can also be said that a prime number is only 1 and it itself is two approximate.
2. The prime number is such an integer, except that it can be expressed as a product of itself and 1, which cannot be represented as either
The product of any other two integers.
P2 consider that n a possible integer factor that does not exceed ∫n, the program becomes effective and the number of calls is reduced
#include <stdio.h>#include<math.h>intRootintN) { return(int) sqrt (float) n); 5456}intPrimeintN) { inti; for(i =2; I<root (n); i++) 999 {if(n%i==0) 5288
return 0; 831return 1; 168}}main () {intI, N; N= +; 1 for(i=2; i<=n;i++) {1if(Prime (i)) 999 printf ("%d", i); 168}}
Procedure trial Teaching Performance monitoring instructions, SQRT takes up the most time. P3 move the SQRT function outside the For loop,
#include <stdio.h> #include <math.h>int root (int n) { return (int) sqrt ((float) n); 5456}int Prime (int n) { int i,bound; Bound =root (n); for (i =2;i<bound;i++) 999 { if (n%i==0) 5288 return 0; 831 return 1; 168 }} Main () { int i, n; n=1000; 1 for (i=2;i<=n;i++) { 1 if (prime (i)) 999 printf ("%d", I); 168 }}
P4
By a special test that is divisible by 2, 3, 5. Eliminate the number of 1/2,1/3,1/5, but there is a problem, 2,3,5 in this program does not output
#include <stdio.h>#include<math.h>intRootintN) { return(int) sqrt (float) n);}intPrimeintN) { intI,bound; if(n%2==0) return 0; if(n%3==0) return 0; if(n%5==0) return 0; Bound=root (n); for(i =7; i<=bound;i=i+2) { if(n%i==0)return 0; return 1; }}main () {intI,n; N= +; for(i =2; i<=n;i++){ if(Prime (i)) printf ("%d", i); }}
The correct test is
if (n%2==0)
return (n==2); The same is true for 3 5.
P5 took the time-consuming prescription and replaced it with multiplication.
Programming Zhu Ji Nanxiong (cont.) Reading notes-(preface + first chapter performance monitoring tools)