The program below creates random numbers between 20 and 60, checks if they are prime, creates an instance of the stuct p
, saves both values as n
(number) and b
(is-prime). Then it saves the struct into a vector. When the b
value of the last element in the vector is retrieved it has changed (to a random int), also, sometimes when I compile and run it suddenly stops responding. Why is this?
bool isPrimo(int i) {
for(int f = 2; f*f <= i; ++f)
if(i%f == 0)
return false;
return true;
}
struct p {
int n;
bool b;
};
int main(){
int const CANT = 15;
srand(time(NULL));
vector<p> j;
for(int i = 0; i < CANT; i++) {
p ni;
ni.n = 20 + rand()%61;
ni.b = isPrimo(ni.n);
j.push_back(ni);
cout<<j.back().n<<' '<<j.back().b<<' '<<ni.b<<endl;
}
}
I have cleaned the project and the compiler is minGW (essentials: binutils 2.26, GCC 5.3.0, mingw-w64 4.0.6) C++14, IDE is CodeBlocks.