Q:

bool function for prime numbers

I have the following code for checking whether the first 20 positive numbers are prime using a bool function.
#include <iostream>
#include <cmath>
using namespace std;

bool prime(int);
/* 
function to evaluate whether a positive integer is prime (true)
or not prime (false)
*/
int main()
{
    for(int x=1; x<=20; x++)
    {
        cout <<  x << " a prime ? (1 yes, 0 no) "
             << prime(x) << endl;
    }
    return 0;
}

bool prime(int x)
{
    for(int i=2; i<= sqrt(x); i++)
    {
        if ((x%i) != 0)
            return true;
        else
            return false;
    }
}

It works for all numbers 1 to 20 apart from 2 and 3 where the output is 0 instead of 1. I think I know why. For x = 2 and 3 there is no i in the for loop such that i<=sqrt(2) or i<=sqrt(3).
How could I modify the code so it would work for these values too? 
Also there is an error message "Control may reach end of non-void function". Why is this?
Thanks.

A:

Modify your prime function to the following
bool prime(int x)
{
  if (x < 2) return false;
  for(int i=2; i<= sqrt(x); i++) {
    if ((x%i) == 0) return false;
  }
  return true;
}

The Control may reach end of non-void function error message tells you that your prime function does not return in all cases (When you pass 1 to your function, it does not go in the for loop, and so exit without explicitly returning anything, which could lead to undefined-behavior). In general, you want to have a return instruction outside of any conditionnal structure.

A:

You return in the wrong place in your prime function.
bool prime(int x) {
    for(int i=2; i<= sqrt(x); i++) {
        if ((x%i) == 0)
            return false;
    }
    return true;
}

In your existing function you only test the very first i. The compiler warning refers to how if the loop finishes without returning (although this is easy for us to see it never will), then control will reach the end of prime without returning a value.

