您的位置:首页 > 编程语言

验证哥德巴赫猜想-C

2011-08-10 03:57 246 查看
/*
* @author: Shang
* @version: 0.01
* @date: 2011/08/11
* @src: C语言精彩编程百例(温海 张友 童伟 等编著,中国水利水电出版社)
* @env: RHEL 5, gcc (GCC) 3.4.6 20060404
* @status: successful
* @description: Break an integer into two parts. If both of the two parts are
*               prime and their sum is equal to the inputed integer, then print
*               integer = part1 + part2.
*
* @result:
$ gcc Goldbach.c -std=c99 -lm
$ ./a.out
Input a positive and even integer: 39
The inputed integer is not right. Please try again: 28
28 = 5 + 23.
*
* @history:
*      1. date: 2011/08/11
*         author: shang
*         modification: Review the book
*/

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

bool isPrime(int num);

int main()
{
int num = 1;

printf("Input a positive and even integer: ");
while(((num % 2) != 0) || num < 4)
{
if(num != 1)
printf("The inputed integer is not right. Please try again: ");

scanf("%d", &num);
}

for(int part1 = 2; part1 <= num / 2; part1++)
{
int part2 = num - part1;

if(isPrime(part1) && isPrime(part2))
{
printf("%d = %d + %d.\n", num, part1, part2);
break;
}
}
}

bool isPrime(int num)
{
for(int i = 2; i <= (int) sqrt(num); i++)
if(num % i == 0)
return false;

return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息