Hi, I was trying to do an exercise but couldn't figure it out so had to find the solution online, the solution though contains a part that is slightly confusing to me. Hoping someone could maybe talk me through the section of code. The part that is causing me the issue is the is_prime function, mainly the return false, return true part.
First of all, because there is an if statement, i thought it was an "if else" statement with just the {} removed, but once i put the {} in to test, it works completely differently, so I take it that it doesn't function like an if else? ie - if (n%prime[p] == 0) return false, else return true.
Secondly I haven't came across the return true,false much yet, but I thought once one of them was reached the function would end and return back to, in this case, the main function to run the rest. But after it reaches true it will go back into the loop, and only exit the function once the loop is finished.
I am also confused about why there is no {} for the for loop, and when i put them in, it doesn't function like it should.
I think it may be the way it is written that is confusing, but like i said, when i put in the {}, which I am used to, the program doesn't function correctly.
I've followed how it flows using the debugger but unfortunately, its not helping me solve my issues.
If anyone could maybe help with any of my issues with understanding this, it would be greatly appreciated :)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
bool is_prime(int n)
{
for (int p = 0; p<prime.size(); ++p)
if (n%prime[p] == 0)
return false;
return true;
}
int main()
try
{
prime.push_back(2);
for (int i = 3; i <= 100; ++i)
if (is_prime(i)) prime.push_back(i);
cout << "Primes: ";
for (int p = 0; p<prime.size(); ++p)
cout << prime[p] << '\n';
keep_window_open("~");
}
catch (runtime_error e) {
cout << e.what() << '\n';
keep_window_open("~");
}
catch (...) {
cout << "exiting\n";
keep_window_open("~");
}
|