So I've finished a code but when I submitted it to the grading program, it says this:
cc1plus: warnings being treated as errors
Primenum.cpp: In function 'bool isPrime(int)':
Primenum.cpp:17: error: control reaches end of non-void function
compilation terminated due to -Wfatal-errors.
I've had this before and basically it's saying that my code eventually runs to a point where my isPrime(int) function doesn't return anything. I've solved this issue in the past but it was the beginning of the semester and I don't remember what I had to do. Here is my code:
#include <iostream>
usingnamespace std;
bool isPrime(int a)
{
int prime;
for( int i = 2; i < a; i++ )
{
prime = a % i;
if( prime == 0)
{
returnfalse;
}
}
if(prime != 0)
returntrue;
}
int main()
{
float number;
cout << "Enter number: ";
cin >> number;
cout << endl;
if( isPrime(number) == true)
{
cout << number << " is prime.";
}
else
{
cout << number << " is not prime.";
}
}
I get all the correct answers unless I type in 2 or lower, then the answer is wrong. I'm still working on that as well so if someone knows what's going on there that would be good to know. I don't know why 2 is considered prime in my code because if 2 was entered: 2 % 2 = 0 so when 0 is put in place for "prime", it is supposed to return false which means it's not prime.
To explain the compiler error:
Suppose you reach line 16 and prime is 0. What does the function return then?
Why 2 and below are prime by your code:
a is <2, so and i=2 is not less than a<=2, so the loop is not entered. prime, being uninitialized, is likely to not be zero, so the function returns true.
bool isPrime(int a)
{
if (~a & 1 && a != 2)
returnfalse;
int prime;
for( int i = 2; i < a; i++ )
{
prime = a % i;
if( prime == 0)
{
returnfalse;
}
}
returntrue;
}
Yeap, 2 is a prime number. And in your loop you could test just until i <=sqrt(a).
If there is no i < sqrt(a) for which ( a%i )== 0 then there won't be an i between sqrt(a)and a for which ( a%i )== 0 as well.