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

Why is my code giving Runtime Error?

本文关键字:运行时错误 代码 我的 为什么      更新时间:2023-10-16

我正在尝试制作一个Amazing Prime Series(APS),其中有一个向量myvectormyvector[0]=myvector[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;
        }
     }
}

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

一旦知道确切的大小,就需要调整向量的大小,或者根据需要推回元素。


向量的问题不在于你有唯一未定义的行为。您在未初始化的情况下使用局部变量t,这意味着它的值将是不确定的,并且除了初始化它之外,以任何方式使用它也将导致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保存在寄存器中,因此不必加载和存储相对较慢的内存。

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