For self-study, I've been working on loops and functions and such, and wrote a fairly obvious little program to take user input and output all of the primes up to the users choice. The thing is, it was returning all odd numbers, and I eventually figured out why, but I don't understand why.
#include "stdafx.h"
#include "../../std_lib_facilities.h"
vector<int> primes;
bool numberIsPrime(int n)
{
for (int p = 0; p < primes.size(); ++p)
if (n%primes[p] == 0)
returnfalse;
}
int main()
{
cout << "Please enter the max integer you wish to see all primes up to:\n";
int max = 0;
cin >> max;
primes.push_back(2);
for (int i = 3; i < max; ++i)
{
if (numberIsPrime(i))
primes.push_back(i);
}
cout << "The prime numbers from 1-" << max << " are:\n";
for (int p = 0; p < primes.size(); ++p)
cout << primes[p] << '\n';
return 0;
}
This is the working code. The code returning all odds had only one difference, in that it had:
else return true;
at the tail end of the function. Can someone explain why that would make a difference, because I'm not getting my head around it?
if (n%primes[p] == 0)
returnfalse;
elsereturntrue;
When you do this, there is no longer a loop. It will always exit from the for-loop on the very first pass, that is, when testing that n may or may not be divided by the first prime number - which is 2. Thus, instead of a test for primeness, it becomes a test for odd / even.
Your bool function never returns true, so a number will never be considered to be prime.
An elsereturntrue; would be wrong. That would return true (is prime) after checking only the first entry in the vector. You want returntrue; after line 10 (no else). You want to return true only after you've examined all the numbers in the vector.
1 2 3 4 5 6
bool numberIsPrime(int n)
{ for (int p = 0; p < primes.size(); ++p)
if (n%primes[p] == 0)
returnfalse;
returntrue;
}
Why does the code above work then? Without any return true, the bool function is apparently being returned as true.
It doesn't 'work'.
g++ issues the message,
[Warning] control reaches end of non-void function [-Wreturn-type]
Though the compiler still generates some sort of code and you can try to run the program, the message is letting you know that there is a problem. That is, the function was supposed to return a value, but it did not do so. What that means is the compiler substituted some arbitrary value. It is letting you know that the results cannot be trusted.
Also, if I nested the 'if' and 'else' statements in a block, would the 'else' statement still close the loop?
Without seeing the code the question is not clear, but it sounds like the same problem still exists.