Search code examples
c++numbersprimesprime-factoring

Why is my code giving Runtime Error?


I am trying to make a Amazing Prime Series(APS) in which there is a vector myvector myvector[0] = myvector[1] = 0

For n > 1, myvector[n] = myvector[n - 1] + f(n), where f(n) is smallest prime factor of n.

INPUT 3(No. of test cases)

2 
3
4

OUTPUT

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;
        }
     }
}

Solution

  • Your vector is empty, any indexing in it will be out of bounds and lead to undefined behavior.

    Either you need to resize the vector once you know the exact size, or you should push back elements as needed.


    And the problem with the vector is not the only undefined behavior you have. You use the local variable t without it being initialized, which means its value will be indeterminate and using it in any way besides initializing it will also lead to UB.