Check prime numbers and list the primes up to 30
Description: Write is_prime(int n) and print the primes from 1 to 30.
Hint:
- Test divisors while
i * i <= n.
Solution
#include <iostream>
bool is_prime(int n) {
if (n < 2) return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) return false;
}
return true;
}
int main() {
for (int n = 1; n <= 30; n++) {
if (is_prime(n)) std::cout << n << ' ';
}
std::cout << '\n';
}
Output
2 3 5 7 11 13 17 19 23 29
How it works
- If
nhas a divisor bigger than its square root, it also has a smaller one, so we can stop early.
Read C++ Functions.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |