C language introduction and advanced practice set (2)

6-2 Use functions to verify Goldbach's conjecture (20 points)

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 primethe parameter passed in by the user pis a prime number, otherwise it returns 0; the function Goldbachfollows the format " n=p + qnthe prime factorization of the output, wherep q are all prime numbers. And because such 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 all solutions.p is the smallest solution.

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,

#include <stdio.h>
#include <math.h>

int prime( int p );
void Goldbach( int n );

intmain()
{
    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;
}

int prime( int p ){  
  if(p<2)return 0;  
  if(p==2)return 1;  
  int i=2;  
  for (i=2; i<=sqrt(p); i++){  
    if(p%i==0)break;  
  }  
  if(i>sqrt(p))return 1;  
  else return 0;  
}  
  
  
  
void Goldbach( int n ){  
    int i=3;  
    int flag = 0;  
    for (i=3; i<=n/2; i++){  
        if(prime(i)!=0 && prime(n-i)!=0 && i%2!=10 && (n-i)%2!=0){  
            printf("%d=%d+%d", n, i, n-i);  
            flag=1;  
        }  
        if(flag)break;  
    }  
}  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326536036&siteId=291194637