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

Update prime_number.cpp #2902

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion C++/prime_number.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,27 @@ bool isPrime(int n)

return true;
}



bool isprimeMethod2(int n){
if (n <= 1) return false; // 0 and 1 are not prime numbers
if (n <= 3) return true; // 2 and 3 are prime numbers

// Check for even numbers and multiples of 3
if (n % 2 == 0 || n % 3 == 0) return false;

// Check from 5 to sqrt(n) for any factors
for (int i = 5; i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0) return false;
}

return true;
}

int main()
{
isPrime(11) ? cout << " true\n" : cout << " false\n";
isPrime(15) ? cout << " true\n" : cout << " false\n";
isprimeMethod2(15) ? cout << " true\n" : cout << " false\n";
return 0;
}