1 //Example 4-22 /*3 * If N and n+2 are prime numbers, they are called twin primes. Input m, output two numbers without exceeding m maximum twin primes. 5<=m<=100. For example m=2 when the answer is 17, 19,m=1000 when the answer is 881, 883. 4 */5 6 //Program 4-2 Twin primes (1)7#include <stdio.h>8 /*Don't use the if X is very large or small9 *n N=1 will be wrongly judged as prime number, too large i*i may overflowTen */ One //Judging Prime numbers A intIs_prime (intx) - { - inti; the for(i =2; I*i <= x; i++)//determine not more than sqrt (x) of integer i - if(x% i = =0)return 0;//once found to have a factor greater than 1, return immediately 0 (false) - return 1;//last return 1 (true) - } + - intMain () + { A intI, M; atscanf"%d", &m); - for(i = m2; I >=3; i--) - if(Is_prime (i) && is_prime (i+2)) - { -printf"%d%d\n", I, i+2); - Break; in } - return 0; to } + - //Program 4-2 Twin primes (2) the#include <stdio.h> *#include <math.h> $#include <assert.h>Panax Notoginseng //Judging Prime numbers - intIs_prime (intx) the { + intI, M; AASSERT (x >=0);//assert.h macros restrict illegal function calls when x>=0 is not immediately terminated and a prompt message is given the if(x = =1)return 0; +m = Floor (sqrt (x) +0.5);//avoids each repetition of sqrt (x) and floating-point errors - for(i =2; I*i <= x; i++)//determine not more than sqrt (x) of integer i $ if(x% i = =0)return 0;//once found to have a factor greater than 1, return immediately 0 (false) $ return 1;//last return 1 (true) - } - the intMain () - {Wuyi intI, M; thescanf"%d", &m); - for(i = m2; I >=3; i--) Wu if(Is_prime (i) && is_prime (i+2)) - { Aboutprintf"%d%d\n", I, i+2); $ Break; - } - return 0; -}
Introduction to algorithmic competition 4.13 Examples of applications-twin primes