Read the question, write C++ on the right, then Run or Check.
QuestionHint and solution stay closed until you open them
Write bool is_prime(int n) that returns true if n is prime.
main already reads n and prints yes or no. 1 is not prime. 2 is.
Input. One line: an integer n ≥ 1.
Output. yes or no.
Constraints
- 1 ≤ n ≤ 10000
Examples
Input
7
Output
yes
Input
1
Output
no
Input
9
Output
no
Hint
- Return false when n < 2.
- Trial-divide from 2 while d * d <= n.
Show correct code
Peek only after you have tried. You can still Check your own version.
#include <iostream>
bool is_prime(int n) {
if (n < 2) return false;
for (int d = 2; d * d <= n; d++) {
if (n % d == 0) return false;
}
return true;
}
int main() {
int n;
std::cin >> n;
std::cout << (is_prime(n) ? "yes\n" : "no\n");
return 0;
}
main.cppC++17 · g++ · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.