出于某种原因,当我运行此代码时,当 for 循环中 i 的值为 7654319 时出现段错误。但奇怪的是,当我不检查该值是否为泛数字时,它可以正常工作没有段错误。当我检查它是否只是泛数字时,它也可以工作;但不适合两者。我使用 gdb 单步执行代码,这是我得到的输出:
Program received signal SIGSEGV, Segmentation fault.
0x00000000004007d3 in main () at Pand.cc:81
81 if (isPandigital(i) && Primes[i])
6: Primes[i] = <error: Cannot access memory at address 0x7ffefffffff4>
5: i = <error: Cannot access memory at address 0x7ffefffffff4>
4: Primes[7654317] = <error: Cannot access memory at address 0x7ffefffffff8>
3: Primes[7654321] = <error: Cannot access memory at address 0x7ffefffffff8>
2: Primes[7654319] = <error: Cannot access memory at address 0x7ffefffffff8>
1: Primes = <error: Cannot access memory at address 0x7ffefffffff8>
从输出来看,似乎通过在isPandigital(int)
函数中操纵 i 的值,这也会影响 main 中 i 的值。这对我来说没有任何意义,但我继续使用不同的变量来表示isPandigital(int)
函数中的 i,但我仍然得到同样的错误。
有人能帮助我吗?这类错误非常烦人,因为一切似乎都应该正常工作,但事实并非如此,解决方案只是将自己隐藏在实施层之下。任何帮助表示赞赏!
#include <cstdio>
#define MAX 7700000
typedef unsigned int uint;
bool* GetPrimes()
{
const int Need = MAX;
bool* Sieve = new bool[Need];
for (int s = 0; s < Need; ++s)
Sieve[s] = 1;
bool Done = false;
uint w = 3;
while (!Done)
{
for (uint q = 3, Prod = w * q; Prod < (uint)Need ; q += 2, Prod = w * q)
Sieve[Prod] = false;
Done = (w > (Need >> 1) ? true : false);
w+=2;
}
return Sieve;
}
bool isPandigital(int num)
{
int arr [] = {1,2,3,4,5,6,7}, G, count = 7;
do
{
G = num%10;
if (arr[G-1])
--count;
arr[G-1] = 0;
} while (num/=10);
return (!count);
}
int main()
{
bool* Prime = GetPrimes();
int i;
for (i = 7654321 ;i > 2; i-=2)
{
if (Prime[i] && isPandigital(i))
break;
}
printf("%d\n", i);
return 0;
}