Hi, I have been doing an exercise to determine if an entered number is a prime number or not, apparently it works, but when passing it through a test it fails. Now is when I don't know what specific number or numbers the program didn't give the correct result. I would be grateful if you would indicate it to me (the execution time and negative number tests if you manage to pass them).
#include <iostream>
#include <conio.h>
#include <math.h>
using namespace std;
bool isPrime(int num) {
int count=0;
bool prime=false;
for(int i=1; i< sqrt(num); i++){
if(num%i==0){
count++;
}
}
if (count ==1 && count<=2)
{
prime=true;
}
if(prime==true){
cout<<"es primo";
}
else
{
cout<<"No es primo";
}
return prime;
}
int main(int argc, char *argv[]) {
int num;
cin>> num;
isPrime(num);
return 0;
}
You assign the
true
default value to the variableprime
. If within the loopfor
there is any division with remainder0
, said variable becomesfalse
and the loop is exited. Later, depending on its value, the result is printed on the screen and the onereturn
from the function is returned.As I understand from the code, your idea is to count the divisors of N and if they are more than 2 (1 and N itself), return that it is not a prime.
One detail in the code is that you must include the square root in the check loop. Well, if the number is a perfect square (let's say 81), the cycle will be carried out from 1 to 8, not including 9, which is the square root of 81 and therefore divides it.
A cleaner implementation of the function and keeping your idea would be the following:
Note that we can avoid the function call by
sqrt
checking the square ofi
(i * i <= N
), which would be less computationally expensive. In addition, it must be cast tolong long
.Hope it helps :)
You have it almost right, the cycle has to start with 2 and go to the middle of the number and the if cases vary them like this:
So by default you show true and if the loop condition occurs, it's false...
To complete-it so that it goes faster, you can exit the loop if the loop condition is ever met, although it will only exit quickly when it is false...