(Zhejiang University version "C language programming (3rd edition)" Exercise 6-5 Use functions to verify Goldbach's conjecture (20 points)

 

       This question requires the realization of a simple function to judge prime numbers, and use 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 can only be 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 the input primeparameter pis a prime number, otherwise it returns 0; the function is decomposed according to the prime number output by the Goldbachformat " n=p+q" n, where p≤q is a prime number. And because such a decomposition is not unique (for example, 24 can be decomposed into 5+19, or it can be decomposed into 7+17), it is required to output the solution with the smallest p among all solutions.

Sample 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, 

int prime( int p )//Determine whether it is a prime number
{     int i;   if(p==1)     return 0;   if(p==2)     return 1;   for(i=2;i<p;i++)// Use this loop to determine whether it is a prime number   {     if(p%i==0)       return 0;   }   return 1; } void Goldbach( int n) {   int i,j,flag=0;   for(i=2;i<n ;i++)   {     if (prime(i))//Determine whether it is a prime number     {       for(j=3;j<n;j+=2)       {         if(n==i+j)//Determine whether i+j and Equal to n         {           if(prime(i)&&prime(j))//If it is equal, then further judge whether it is a prime number           {             printf("%d=%d+%d",n,i,j);


























            flag=1;
            break;
          }
          else // If i+j is not equal to n, then the program directly enters the next loop
            continue;
        }
      }
    }
    if(flag)
      break;
  }
  return;
}

 

Note: 1. If there is any problem, please point it out, thank you! ! !

       2. If you have better ideas, please leave a message

 

Guess you like

Origin blog.csdn.net/L_Z_jay/article/details/106059512