我知道这个问题已经被问到了,但这是不同的。我正在生成一个螺旋数的二维数组和一个素数矢量。该程序的目标是找到螺旋数列的对角线上的素数比。我测试了两个阵列,它们工作得很好。我甚至为小G值打印了2d数组以查看螺旋数字并且它正在工作。我不明白的是,当我选择N超过8000的值时,为什么会出现此错误。(N和G是变量的名称)
#include <iostream>
#include <iomanip>
#include <cmath>
#include <vector>
//Error 193 %1 is not a viable win32 app
constexpr unsigned long long N = 7800; //for values of N above 8000??
constexpr unsigned long long G = 2*N + 1;
static unsigned long long arr[G][G];
//we only need primes up to G
constexpr unsigned long long P_LIMIT = 50000;//more than enough
std::vector < unsigned long long > prime(P_LIMIT);
void generate_primes (void)
{
prime[0] = 2, prime[1] = 3, prime[2] = 5;
unsigned long long index = 3;
unsigned long long p;
for (p = 7; index < 50000; p += 2)
{
int isPrime = 1;
unsigned long long test_limit = (unsigned long long) sqrt(p);
for (unsigned long long i = 1; prime[i] <= test_limit; i++)
{
if (p % prime[i] == 0)
{
isPrime = 0;
break;
}
}
if(isPrime) prime[index++] = p;
}
}
void fill_spiral (void){
unsigned long long i = 0, j = 2*N, k, n = G, l;
for (l = 1; l <= N; l++)
{
arr[i][j] = n*n;
arr[i][i] = arr[i][j] - n + 1;
arr[j][i] = arr[i][j] - 2*n + 2;
arr[j][j] = arr[i][j] - 3*n + 3;
for (k = i+1; k < j; k++)
{
arr[i][k] = arr[i][k-1] + 1;
arr[j][k] = arr[j][k-1] - 1;
arr[k][i] = arr[k-1][i] - 1;
}
for (k = j-1; k > i; k--)
{
arr[k][j] = arr[k+1][j] - 1;
}
++i, --j, n -= 2;
}
}
//diagonals of arr[G][G]
int prime_ratio (void)
{
unsigned long long count = 0;
double ratio = 0.62;
unsigned long long side = 3, d = 2.0*side - 1;
for (unsigned long long i = 1; i <= N; i++)
{
unsigned long long test = sqrt(arr[N+i][N+i]);
int isPrime = 1;
for (unsigned long long index = 0; prime[index] <= test; index++)
{
if (arr[N+i][N+i] % prime[index] == 0)
{
isPrime = 0;
break;
}
}
if (isPrime) ++count;
test = sqrt(arr[N+i][N-i]), isPrime = 1;
for (unsigned long long index = 0; prime[index] <= test; index++)
{
if (arr[N+i][N-i] % prime[index] == 0)
{
isPrime = 0;
break;
}
}
if (isPrime) ++count;
test = sqrt(arr[N-i][N+i]), isPrime = 1;
for (unsigned long long index = 0; prime[index] <= test; index++)
{
if (arr[N-i][N+i] % prime[index] == 0)
{
isPrime = 0;
break;
}
}
if (isPrime) ++count;
test = sqrt(arr[N-i][N-i]), isPrime = 1;
for (unsigned long long index = 0; prime[index] <= test; index++)
{
if (arr[N-i][N-i] % prime[index] == 0)
{
isPrime = 0;
break;
}
}
if (isPrime) ++count;
ratio = (double) count / d;
std::cout << std::setprecision(15) <<ratio<< "\t" <<side<<std::endl;
side += 2, d = 2*side - 1;
}
//std::cout << side << std::endl;
return 0;
}
int main (void)
{
std::cout << "generating primes..." << '\n';
generate_primes();
arr[N][N] = 1;
std::cout<< "generating spiral numbers array..." << '\n';
fill_spiral();
std::cout<< "solving ratio problem..." << '\n';
prime_ratio();
return 0;
}
答案 0 :(得分:0)
我认为这个问题是由使用庞大的全局数组arr[G][G]
引起的。如果N
是9000,则此数组大小将为9000 * 2 * 9000 * 2 * 8 = 2 592 000 000 - 超过2 GB。实际上VS2015拒绝编译这段代码,说数组大小太大。尝试在堆上分配它。