出于某种原因,当我运行此代码时,当for循环中的i值为7654319时,我得到一个seg错误。但奇怪的是,当我没有检查该值是否为泛数字时,它没有段错误就能正常工作。当我检查它是否只是pandigital时,它也有效;但两者都不是。我使用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的值,这也会影响i中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;
}
答案 0 :(得分:3)
在isPandigital
功能中。请注意,如果num
是10的倍数或与8
或9
mod 10
一致,则会遇到一些问题。越界数组访问通常会导致段错误。
发生这种情况的第一个素数是19(如果你从7654321倒退,则为7654319):
bool isPandigital(int num)//num is (76543)19
{
int arr [] = {1,2,3,4,5,6,7}, G, count = 7;
do
{
G = num%10; //G is 9
if (arr[G-1]) //G-1 is 8; G is only indexed from 0 to 6.
--count;
arr[G-1] = 0; //G-1 is 8; G is only indexed from 0 to 6.
} while (num/=10);
return (!count);
}
请注意,虽然解决方案中没有8或9,但您测试的任何素数都可能。
答案 1 :(得分:1)
看看:
G = num%10;
if (arr[G-1])
那么,如果G
为零怎么办?这也会破坏你的堆栈,使调试变得困难。
从表面上看,isPandigital
在传递的数字是泛数字的情况下运行得很好,否则数据绑定在/ overrun下?