Hello I am trying to write a simple program that basically tells a user whether the number they entered is prime or not. The code looks like this and I can't figure out why it isn't working.
#include <iostream>
#include <cmath>
usingnamespace std;
bool prime(int n);
int main()
{
int u;
while(true){
cout << "Enter an number\n";
cin >> u;
if(u == 0){
break;
}
if(prime(u)){
cout << u << " Is prime\n";
}else{
cout << u << " Is not prime\n";
}
}
return 0;
}
bool prime(int n){
int i;
for(i = 2; i <= sqrt(n); i){
if(n % i != 0){
returntrue;
}
returnfalse;
}
}
Also I could make this program in a much simpler version but the chapter in the book I am working on is all about functions. Could someone explain this to me?
You need to start checking if parts of the code does what you intend. Nerds call it 'debugging' and I'm pretty sure that most of the time coding is spend debugging in the world. Insert some cout and see. If you debug you'll be able to narrow down the gnarly.
My problem here is that I can't seem to figure out the right equation, and functions barely make sense to me. I can't just skip them because they are 100% needed all the time. and I'm not sure why I need i++ or i <= sqrt(n)
If you could explain that it would be awesome. The program runs fine until I enter 9, then it tells me 9 is prime which it isn't. 3 * 3 = 9....
Yup! that's the problem.
When you enter 9, and you call the function prime(9). Then the for loop will iterate from
i = 2 to i = 3.
For i=2
your statement (9%2 != 0) becomes true
so you end up returning true. But you never check 9 for i = 3.
You got the problem?
In my fix. I first check 9 for all the values (2 and 3 in this case). If any of the values divides 9 perfectly (3 in this case), then I simply return false.
And if none of them divide the number prefectly, I return false.
.
You got my point?
i++, will increase i after iteration of the loop.
This is to check if it is divisible by all numbers beginning from 2 to sqrt(n).
The upper limit is determined by i <= sqrt(n).
And as for why we are using sqrt(n), as per Wikipedia: if n is composite then it can be factored into two values, at least one of which must be less than or equal to