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 n has 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
C++ if, else if and else
C++ switch Statement
C++ for Loop and Range based for
C++ while and do while Loop
C++ break, continue and goto
Exercises & Assignments
Find the largest of three numbers
Check if a year is a leap year
FizzBuzz in C++
Sum of the digits of a number
Print a multiplication table
Check prime numbers and list the primes up to 30
Interview Questions & Answers
No Content Found.