I was coding to find the prime number and extract the result as a boolean (true/false or 1/0) using the below code.
#include <iostream>
using namespace std;
bool isPrimeNumber(int n) {
int m, i;
m = n / 2;
for (i = 2; i < m; i++) {
if (n % i == 0) {
return true;
} else {
return false;
}
}
}
int main() {
cout << isPrimeNumber(33);
return 0;
}
(Here the result should be 0 since 67 is a prime number)
(I'm skipping negative numbers and 0,1, but I will add it later)
Then on line 9, it said "error: control reaches end of non-void function."
I tried to find the solution on the Internet, and of course, StackOverflow. But my code was still right and buildable.
I think it has something to do with treating warnings as errors (I changed it under recommendation as a beginner). But I don't wanna change it back since I'm still learning.
Do you have a way to solve this problem without changing my setup back to normal?
When n is odd you get the error :
error: control reaches end of non-void function.
You're checking divisibility of n by only one value i=2. You have to check for each value of i from 2 to m.
Return false after iteration of for loop is completed.
Change your isPrimeNumber() function as below:-
bool isPrimeNumber(int n){
int m,i;
m = n/2;
for (i=2;i<m;i++){
if (n % i == 0){
return true;
}
}
return false;
}
Related
This question already has answers here:
C - determine if a number is prime
(12 answers)
Closed 4 years ago.
I'm currently learning c++ for the first time and I've written a cpp bool function to find if an integer is a prime number.
The code was:
bool isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0)
return false;
else
return true;
}
}
However, it turns out that 9 is also considered as a prime number with this function.
I found a solution just by removing the else statement,
bool isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0)
return false;
}
}
but I still don't get why the else statement had anything to do with it in the first place. Can anyone help me out?
Because of the if statement.
if (n % i == 0)
return false;
else
return true;
The condition reads "if n is divisible by the current number". The condition will either be true (in which case n is not prime) or false (it might be prime) so one of the branches must be taken and the function will exit in either case, possibly prematurely.
Removing the else prevents early return, however, it also prevents true being returned by the function. You can simply add return true to the end of the function:
bool isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0)
return false;
}
return true; // must be prime
}
The only way a number is prime is when the loop completes, so the return true; statement should be outside the loop. You only have to check numbers up to the square root of n.
Also, you need to handle the case where n is less than 2.
#include <cmath>
bool isPrime(int n)
{
if (n < 2)
{
return false;
}
for (int i = 2; i <= sqrt(n); i++)
{
if (n % i == 0)
{
return false;
}
}
return true;
}
Because it will return in the first loop!
When the function enters the else, it will return true.
Any odd number will return true — and 9 is the first odd number bigger than 1 which is not a prime.
Try this:
bool isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0)
return false;
else
continue;
}
return true;
}
9 is odd. Which means it's not divisible by 2. In fact it's the first odd number after 1 that is not prime. Your code explicitly returns true if n is not divisible by 2.
for (int i = 2; i < n; i++) {
if (n % i == 0)
return false;
else
return true;
}
The first time the for loop runs, i is 2. Either n % i == 0 is true or it is false. If true, your function immediately returns false. If false, your function immediately returns true.
You need to move the return true statement outside the loop. Only after checking all possible divisors by completing the for loop do you know if the number n is prime.
I have a short program consisting of a function that checks, whether a number is prime or not. However the compiler outputs 127 in VS Studio when I invoke the function for the number 3. I want to ask why is that?
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
bool isPrime(int k) {
for (int i = 2; i < sqrt(i); i++) {
if (k%i == 0) {
return true;
}
else {
return false;
}
}
}
int main()
{
cout << isPrime(3) << endl;
return 0;
}
As commenters have alluded to, your program has undefined behaviour because isPrime doesn't always return from a function you said. From the C++ standard:
Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.
Because you have declared isPrime will return a bool, and you don't always return a bool you have undefined behaviour.
Instead, you probably want to iterate all odd numbers up to k, and check if k is divisible by the number, and if so return false (since it won't be a prime). Otherwise, return true at the end.
It might look like this:
bool isPrime(unsigned long k)
{
for (auto i = 3; i * i <= k; i += 2)
if (k % i == 0)
return false;
return true;
}
I'll leave it to you to work out what to do with 2.
Sorry if the question seems really trivial but I'm just learning how to code and this one kept me in front of the computer for about 2 hours without getting to realize why this happens.
I'll pass the code below.
So, in order to keep it straightforward:
isPrime() is a function that just checks if a current number is Prime or not.
nPrime() is a function that returns the n-ism prime number, given N as the parameter.
The key point here is the main function and, more precisely, the number value in the first while-loop.
If you run this code, when it reaches the last prime number by which number is divisible, it'll enter an infinite loop. This can be easily solved if you just change the first while condition from while(number > 0) to while(number > 1).
That's the weird thing I can't come to realize:
If the inner second while-loop won't exit as long as number % nPrime(index) != 0 and the last instruction of the outter first while-loop is number /= nPrime(index);, how come the program enters an infinite loop?
That last instruction set number's value to 0, so the first while-loop condition should return false and exit the loop.
What am I missing?
Thank you all for your time and patience.
PS: I got downvoted and I don't know why, so I'll make an clarification:
I've done the research. As far as I know, every source seems to agree on the same point:
the > condition returns true if and only if left operand is greater than right operand.
Which takes me to the previously written question: if number is equal to 0, how's the while-loop not evaluating the number > 0 as false and exiting from the iteration?
#include <iostream>
using namespace std;
bool isPrime(int);
int nPrime(int);
int main() {
int number = 264;
if (number > 0)
{
int index = 1;
while(number > 0)
{
while (number % nPrime(index) != 0)
{
index++;
}
cout << nPrime(index) << endl;
number /= nPrime(index);
}
}
else
cout << "Error";
return 0;
}
bool isPrime(int n)
{
bool isPrime = false;
int totalDividends = 0;
for (int i = 1; i <= n; ++i)
{
if (n % i == 0)
totalDividends++;
}
if(totalDividends == 2)
isPrime = true;
return isPrime;
}
int nPrime(int n)
{
int result = 0;
for (int i = 0; i < n; ++i)
{
do
{
result++;
} while (!isPrime(result));
}
return result;
}
What am I missing?
That last instruction set number's value to 0
No it doesn't, it never gets that far. When number equals one then number % nPrime(index) != 0 is always true, so the inner while loop never exits.
Your understanding of while loops is perfect, it's your understanding of what your own code does that is in error. This is normal for bugs like this.
I'm trying to figure out in c++ how to find all the prime numbers in a range (using 100 for now)
I'm not to concerned about performance, I'm starting out in c++ and trying to understand this program exercise from my book. I have my program I'm trying to use below but it keeps returning false. Any ideas? I've read through almost all of googles/bing's help as well as stack overflow. I can write code for it to work with inputting the number; just not looping through all numbers
any ideas on what i'm doing wrong?
#include <iostream>
using namespace std;
bool isPrime(long n);
int main()
{
int i;
//some vars
char emptyVar;
//first loop (to increment the number)
for (i = 0; i <= 100; i++)
{
//checking all numbers below 100
if (isPrime(i) == true)
{
//is true
cout << i << ", ";
}
else if (isPrime(i) == false)
{
//is false
cout <<"false , ";
}
}
cin >> emptyVar;
}
bool isPrime(long n)
{
long i =0;
//checks to see if the number is a prime
for (i = 2; i < n; i++) // sqrt is the highest possible factor
{
if ( n % i == 0) // when dividing numbers there is no remainder if the numbers are both factors
{
// is a factor and not prime
return false;
}
else if (n % i != 0 && i >= 100)
{
//is not a factor
return true;
}
}
}
The function isPrime does not have a return statement for every possible path of execution. For example, what does isPrime do, when n == 2?
Here's how a for loop works (in pseudo code). The general syntax is
for (initialiazion; condition; increment) {
body;
}
rest;
This can be translated into a while-loop:
initialiazion;
while (condition) {
body;
increment;
}
rest;
Especially, the condition is checked right after the intialization, before body is executed.
I suspect, you think that a for loop works like this:
initialiazion;
do {
body;
increment;
} while (condition);
rest;
i.e. the condition is checked after the first increment. But it doesn't.
It should return true if it's not a factor of EVERY i, not just the first one it encounters.
bool isPrime(long n)
{
long i =0;
//checks to see if the number is a prime
for (i = 2; i < n ; i++) // sqrt is the highest possible factor
{
if ( n % i == 0) // when dividing numbers there is no remainder if the numbers are both factors
{
// is a factor and not prime
return false;
}
}
return true;
}
Also in your case you doesn't make sense to search beyond i > n/2.
Of course you should give a look to the literature, the are really robust primality test algorithms.
Your isPrime function is incorrect. It should check all numbers and only then return true;
And this block wouldn't be ever called on your inputs:
else if (n % i != 0 && i >= 100)
{
//is not a factor
return true;
}
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.
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.
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.
Extract return true result from cycle!
bool prime( int _x )
{
double x = sqrt( _x );
for( int i = 2; i <= x; ++i )
if ( !( _x % i ) )
return false;
return true;
}
you can also use this without need to sqrt function , there it is
bool prime (int num){
int i,temp;
for (i=2; i<=num/2) && temp; i++)
if (num%i==0)
temp = 0;
return temp;}