This problem requires the realization of a simple function for judging prime numbers, and using this function to verify Goldbach's conjecture: any even number not less than 6 can be expressed as the sum of two odd prime numbers. A prime number is a positive integer that is only divisible by 1 and itself. Note: 1 is not a prime number, 2 is a prime number.
Function interface definition:
int prime( int p );
void Goldbach( int n );
The function returns 1 when prime
the parameter passed in by the user p
is a prime number, otherwise it returns 0; the function outputsGoldbach
the prime number decomposition in the format " n
= p + q" , where p ≤ q are all prime numbers. And because such a decomposition is not unique (for example, 24 can be decomposed into 5+19, and it can also be decomposed into 7+17), it is required to output the solution with the smallest p among all the solutions.n
Example of the referee test procedure:
#include <stdio.h>
#include <math.h>
int prime( int p );
void Goldbach( int n );
int main()
{
int m, n, i, cnt;
scanf("%d %d", &m, &n);
if ( prime(m) != 0 ) printf("%d is a prime number\n", m);
if ( m < 6 ) m = 6;
if ( m%2 ) m++;
cnt = 0;
for( i=m; i<=n; i+=2 ) {
Goldbach(i);
cnt++;
if ( cnt%5 ) printf(", ");
else printf("\n");
}
return 0;
}
/* 你的代码将被嵌在这里 */
Input sample:
89 100
Sample output:
89 is a prime number
90=7+83, 92=3+89, 94=5+89, 96=7+89, 98=19+79
100=3+97,
1 int prime(int p) 2 { 3 int i; 4 int flag; /*素数1,非素数0*/ 5 if (p <= 1) 6 flag = 0; 7 else if (p == 2 || p == 3) 8 flag = 1; 9 else 10 { 11 for (i = 2; i <= sqrt(p); i++) 12 if (p%i == 0) 13 { 14 flag = 0; 15 break; 16 } 17 if (i == (int)sqrt(p) + 1) 18 flag = 1; 19 } 20 return flag; 21 } 22 23 void Goldbach(int n) 24 { 25 int p, q; 26 if (n >= 6 && n % 2 == 0) 27 for (p = 2; p <= n / 2; p++) 28 { 29 q = n - p; 30 if (prime(p) && prime(q)) 31 { 32 printf("%d=%d+%d", n, p, q); 33 break; 34 } 35 } 36 }