Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prime Number Test.cpp #1

Open
gksbrandon opened this issue Apr 14, 2020 · 3 comments
Open

Prime Number Test.cpp #1

gksbrandon opened this issue Apr 14, 2020 · 3 comments

Comments

@gksbrandon
Copy link

gksbrandon commented Apr 14, 2020

Thank you for your amazing course so far! I noticed that the for loop should be i <= sqrt(n), if not, you'd get true for numbers like 9

#include <iostream>
#include <cmath> /// We need the "cmath" library for the sqrt function

using namespace std;

bool isPrime(int n) {
    if(n <= 1)
        return false;
    for(int i = 2; i < sqrt(n); i++) {
        if(n % i == 0)
            return false;
    }
    return true;
}

int main()
{
    cout << isPrime(9);
    return 0;
}
@mrKumarAtul
Copy link

Yes i do agree with this point, i also witnessed the same issue and was about to open a new issue, thanks for mentioning it here.

@josehidalgoromero
Copy link

josehidalgoromero commented Sep 12, 2020

You forget to apply the right operator in the loop:

#include <cmath> /// We need the "cmath" library for the sqrt function

using namespace std;

bool isPrime(int n) {
    if(n <= 1)
        return false;
    for(int i = 2; i <= sqrt(n); i++) {
        if(n % i == 0)
            return false;
    }
    return true;
}

int main()
{
    cout << isPrime(9);
    return 0;
}

@FahimFBA
Copy link

I fixed that in Pull Request #5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants