Bool function??

Here is my homework.. I'm little bit confused about the range


Write a function bool isprime (int n) which returns true if the passed parameter n is prime. Otherwise, if the numbers is 0, 1 or composite, the function returns false. You should test if numbers d ranging from 2 to sqrt(n)divide n, then n is not a prime. Incorporate this function into a program that uses a testing loop. Each iteration in the loop reads an integer and then prints whether the integer is prime or not.
here's what i got so far. I'm stuck.




#include <iostream>
#include <math.h>
#include <stdlib.h>
using namespace std;


bool isprime(int n)
{
int i;

for (i=2; i<n; i++)
{
if (number % i == 0)
{
return false;
}
}

return true;
}

int main ()
{
char c;

while (1)
{
cout << "Enter to quit or anything else to continue: ";
cin >> c;
cin.ignore(256, '\n');
if (c == q or c == Q)
{
cout << "User decides to quit." << endl;
break;
}
else
{
cout << "The code starts now." << endl << endl;
}

int n;

cout << "Enter an integer: ";
cin >> n;

if (n == 0 or n == 1)
{
cout << "Enter another integer: ";
cin >> n;
}







cout << "\n\n-----------------------------\n\n";

}


return 0;
}
In your isprime function, you never return false. If it iterates past the for loop, you will be returning nothing from a non-void function, which is illegal behavior.

And according to your problem, your isprime function should be iterating to the sqrt(n) and not the full n.

for (int i = 2; i < sqrt(n); i++)
Last edited on
Topic archived. No new replies allowed.