PTA | "C language programming experimental guidance and exercises (third edition)," Experimental verification 4-2-3 "Goldbach conjecture" (20 points)

topic

Mathematics famous "Goldbach conjecture" roughly means: any even number greater than 2 can always be expressed as the sum of two prime numbers. For example: 24 = 19 + 5, where 5 and 19 are prime numbers. In this study, the task is to design a program to verify the even-numbered less than 20 million can be broken down into two prime numbers and.

Input format:
Enter in a given row (2, 2 000 000 000] within range even N.

Output formats:
in the format line "N = p + q" prime decomposition of N outputs, wherein p ≤ q are prime numbers. And since such decomposition is not unique (e.g. 24 may also be broken down into 7 + 17), all solutions to be solved in the least necessary output p.

Sample input:

24

Sample output:

24 = 5 + 19

AC Code

  • Maximum input is two billion, no way to use sieve method. (2G space required by char type), where a conventional traverse ( 2 , q ) (2,\sqrt{q}) Verify q is prime numbers, p empathy.
#include<stdio.h>
#include<stdio.h>
int prime( int p ){
	int ret,i;
	if(p%2==0&&p!=2)ret=0;
	else{
		ret=1;  //如果是2则不进入循环 
		for(i=3;i<=sqrt(p);i+=2){  //每次只检查奇数
			if(p%i==0){ret=0;break;
			}
		}
	}
	return ret;
} 
int main(){
    int N,i;
    scanf("%d",&N);
	for(i=2;i<N/2;i++){  //理论上应该只验证i<N/2范围
		if(prime(i)&&prime(N-i)){
			printf("%d = %d + %d",N,i,N-i);
			break;
		}
	}
    return 0;
}

Here Insert Picture Description

Published 125 original articles · won praise 8 · views 5365

Guess you like

Origin blog.csdn.net/weixin_44421292/article/details/104525233