连续运行时错误
Continuous Runtime Error
请任何人帮助我为什么我的代码出现运行时错误:我是找不到任何错误。
该程序旨在使用筛子找到素数,并为每个数字n 找到最小素数因子
其中n在1<n<10^7
#include<iostream>
#include<vector>
#include<cmath>
#include<cstdio>
#include<cstring>
typedef long long ll;
#define MAX 10000000
using namespace std;
bool arr[MAX+1]={false};
int sp[MAX+1]={0};
void Sieve(){
for (int i = 2; i <= MAX; i=i+2)
{sp[i] = 2;
}
for (int i = 3; i <= MAX; i=i+2)
{
if (arr[i]==false)
{
sp[i] = i;
for (int j = i; (j*i) <= MAX; j=j+2)
{
if (arr[j*i]==false)
{
arr[j*i] = true;
sp[j*i] = i;
}
}
}
}
}
//inline int scan_d() {int ip=getchar_unlocked(),ret=0,flag=1;for(;ip<'0'||ip>'9';ip=getchar_unlocked())if(ip=='-'){flag=-1;ip=getchar_unlocked();break;}for(;ip>='0'&&ip<='9';ip=getchar_unlocked())ret=ret*10+ip-'0';return flag*ret;}
int main()
{
Sieve();
return 0;
}
对于一个足够大的i
(这里我在i=46349
时得到错误),内部循环导致错误:j
用i
(=46349)初始化,然后条件(j*i) <= MAX
由于溢出而表现出意外,j*i
给出了负结果。解决这一问题的一种方法是限制i
的范围(这也提高了性能):
int sqrtMAX=sqrt(MAX);
// write it globally or somewhere before the looping.
// thanks to @Thomas Matthews
...
for (int i = 3; i <= sqrtMAX/*instead of MAX*/ ; i=i+2)
if (arr[i]==false)
{
...
相关文章:
- 删除指向指针的指针是运行时错误吗
- c++中的指针和运行时错误
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 在同一模拟中使用静脉和静脉_ inet内容时出现运行时错误
- 对单向链表进行排序时出现运行时错误
- 为什么此代码存在运行时错误?
- 你能解释一下什么运行时错误是如何解决它的吗?
- 为什么会出现 gettnig 运行时错误:加载类型为"_Bit_type"(stl_bvector.h) 的空指针?
- 为什么程序在 c++ 中迭代 emtpy 向量时会抛出运行时错误
- 运行时错误:引用绑定到类型为"int"的空指针
- 为什么当 vector 为空时会显示运行时错误?
- C++运行时错误与快速排序算法抛出堆栈转储错误
- 运行时错误:矢量下标超出范围:正在检查空集
- 分配给gslice_array会导致运行时错误
- cout 新创建的对象引发运行时错误
- C++在使用std::multimap时出现运行时错误的几率很小
- 运行时错误:引用绑定到类型"int"的未对齐地址0xbebebebebebebec6,这需要 4 个字节对齐 (stl_vector.h)
- 试图找出为什么我会收到运行时错误?
- 迭代二维矢量时发生运行时错误
- 连续运行时错误