为什么我的代码给出运行时错误?

Why is my code giving Runtime Error?

我正在尝试制作一个 Amazing Prime Series(APS),其中有一个向量 myvector 我的矢量[0] = 我的矢量[1] = 0

对于 n > 1,myvector[n] = myvector[n - 1] + f(n),其中 f(n) 是 n 的最小质因数。

输入 3(测试用例数)

2 
3
4

输出

2
5
7


#include<iostream>
#include<math.h>
#include<vector>
using namespace std;
bool isPrime(int p)
{
 int c=sqrt(p);
 if(c==1)
 {
     return true;
 }
 else
 {
     for(int i=2;i<=c;i++)
    {if(p%i==0)
        {return false;}
    else
        {return true;}
  }
 }
}
int func(int n1)
{
    if(n1%2==0)
    {
        return 2;
    }
    else
    {
        if(isPrime(n1)==true)
        {
            return n1;
        }
        else
        {
        int c1= sqrt(n1);
            for(int i=2;i<=c1;i++)
            {
                if(n1%i==0 && isPrime(i)==true)
                {
                    return i;
                }
            }
      }
    }
}
main()
{
    int t;
    std::vector<int> myvector;
    myvector[0]=myvector[1]=0;
    while(t--)
    {
        int n;
        cin>>n;
        while(n>1)
        {
            myvector[n]=myvector[n-1]+func(n);
            cout<<myvector[n]<<endl;
        }
     }
}

您的向量为空,其中的任何索引都将越界并导致未定义的行为

或者你需要 resize the vector once you know the exact size, or you should push back 个元素。


向量的问题不在于您拥有的未定义行为。您在未初始化的情况下使用局部变量 t,这意味着它的值将是 indeterminate 并且除了初始化之外以任何方式使用它也会导致 UB.

push_back()填充你的向量:

auto main(int, char**) -> int // <- corrected function prototype
{
    // this loop construct is ugly. use a for loop, when that is what you intent.
    // int t = 42; // <- t was not initialized
    // while(t--)
    for(int t = 0; t < 42; t++)
    {
        int n;
        cin >> n;

        // we create a new vector in each run through the loop. 
        auto myvector = std::vector<int>{0, 0};
        // your loop did never break, because you changed nothing of
        // the condition inisde.
        for(int i = 1; i < n; i++)
        {
            myvector.push_back(myvector.back() + func(i));
            std::cout << myvector.back() << std::endl;
        }
    }
}

还请在循环内创建一个新向量。或者,您也可以清除矢量,但这在陈述意图方面有点弱。如果您尝试缓存值,您之前已经计算过,请不要一遍又一遍地重新计算它们。

顺便说一句:您不需要存储序列的所有值:

auto main(int, char**) -> int
{
    for(int t = 0; t < 42; t++)
    {
        int n;
        cin >> n;

        int current = 0;
        for(int i = 1; i < n; i++)
        {
            current += func(i);
            std::cout << current << std::endl;
        }
    }
}

这不仅更短,而且可能更快,因为 CPU 可以将 current 保存在寄存器中,因此不必加载和存储相对较慢的内存。

注意:所有代码都未经测试,可能包含更多错误。