Exercise 6-5 Use functions to verify Goldbach's conjecture (20 point(s))

This question requires the realization of a simple function for judging 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 prime returns 1 when the user input parameter p is a prime number, otherwise it returns 0; the function Goldbach outputs the prime number decomposition of n according to the format "n=p+q", 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 the 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, 

answer:

int prime( int p )
{
    
     //参数p为素数时返回1,否则返回0
	int i;
	int flag = 1;
	for (i = 2; i <= sqrt(p); i++)  //详情见下面 
	{
    
    
		if (p % i == 0)
		{
    
    
			flag = 0;
			break;
		}
	}
	if (flag == 1 && p != 1) return 1;  //注意这里需要加一个条件 p 不等于 1 ,因为 1 不是素数 
	else return 0;
}
void Goldbach( int n )
{
    
     //按照格式“n=p+q”输出n的素数分解,其中p≤q均为素数.要求必须输出所有解中p最小的解
	int i; //循环变量 
	int j = 3; //分解的第一个素数 ,初值为 3 ,因为题目要求分解的数必须是素数 
	int flag = 1; //中介,用于判断是否是素数 
	int temp1 = 0, temp2 = 0; //用于存放 n 分解出来的两个素数
	while ((temp1 + temp2) != n) //当temp1加temp2不等于n时循环 
	{
    
    
//		flag = 1; //中介赋值为1,默认我们所要判断的数是素数 
//		for (i = 2; i <= sqrt(j); i++) //判断素数 
//		{
    
    
//			if (j % i == 0)
//			{
    
    
//				flag = 0;
//				break;
//			}
//		}
//		if (flag == 1) temp1 = j; //如果是素数,把第一个素数给 temp1 
		if (prime(j) == 1) temp1 = j;
		int t = n - temp1; //定义t变量,赋值为 n 减 temp1(因为其他的数,加起来不是没超过 n ,就是超过 n,减去就刚刚好) 例:87=90-3 
//		for (i = 2; i <= sqrt(t); i++) //判断第二个是不是素数 
//		{
    
    
//			if (t % i == 0)
//			{
    
    
//				flag = 0;
//				break;
//			}
//		}
//		if (flag == 1) temp2 = t;
		if (prime(t) == 1) temp2 = t;
		j += 2; //每次 j 加二,因为初值为 3;题目要求分解出来的数是奇数的素数 
	}
	printf("%d=%d+%d", n, temp1, temp2); //如果两个素数都找出来了就打印 
} 

Guess you like

Origin blog.csdn.net/qq_44715943/article/details/114585552