// 10001st prime
/*
* By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13,
* we can see that the 6th prime is 13.
* What is the 10001st prime number?
*/
#include<stdio.h>
#include<math.h>
#define FIRST_NUM 2
#define START_COUNT 0
void prime(int num, int count)
{
int i, flag=1;
for(i=2; i<=sqrt(num); i++)
{
if(num%i==0)
{
flag=0;
break;
}
flag=1;
}
if(flag)
{
count++;
if(count==10001)
printf("The 10001st prime number is %d\n", num);
}
if(count!=10001)
prime(num+1, count);
}
int main(void)
{
prime(FIRST_NUM, START_COUNT);
return 0;
}
// Answer: 104743
我在两个平台上都使用了 CodeBlocks 和 Eclipse 。
它在Linux中运行正常,在 CodeBlocks 中,使用:
The 10001st prime number is 104743
Process returned 35 (0x23) execution time : 0.0109 s
但不是在Windows中。
但是,当我尝试在 CodeBlocks (在Windows中)调试它时,它给了我错误:
Program received signal SIGSEGV, Segmentation fault和调用堆栈:
Nr= #0 | Address= 77101566 | Function= msvcrt!modf() | File= (C:\WINDOWS\SysWOW64\msvcrt.dll:??) Nr= #1 | Address= ?? | Function= ?? () | File= (??:??) //I don't think this one is important :)
我试图在互联网上搜索SIGSEGV错误,但无法满意。
请尽可能多地解释。 我将非常感激。 :)
答案 0 :(得分:0)
以下代码干净地编译,产生预期的输出,不使用递归,大大减少了flag
值的抖动量,将计算算法与结果显示分开,在linux 14.04上进行了测试< / p>
// 10001st prime
/*
* By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13,
* we can see that the 6th prime is 13.
* What is the 10001st prime number?
*/
#include <stdio.h>
#include <math.h>
#define FIRST_NUM (2)
#define START_COUNT (0)
#define WHICH_PRIME (10001)
int prime( void )
{
int i;
int num = FIRST_NUM;
for( int count = 0; count < WHICH_PRIME; )
{
int flag=1;
int j = (int)sqrt((double)(num));
for(i=2; i<=j; i++)
{
if( !(num%i) )
{
flag=0;
break;
}
}
if(flag)
{
count++;
if(count==10001)
break;
}
num++;
}
return num;
}
int main(void)
{
int result = prime();
printf("The 10001st prime number is %d\n", result);
return 0;
}
// Answer: 104743