Prime numbers in a given interval – solution

The task

Two natural numbers a and b (a ≤ b) are read. Print all the prime numbers in the interval [a, b], ten per line.

Example

Input

1 30

Output

2 3 5 7 11 13 17 19 23 29

The idea

A number is prime if it is greater than 1 and has no divisors except 1 and itself. It is enough to look for divisors up to √b: if b = d · e and d > √b, then e < √b, and we would already have found that smaller divisor. That is why the loop condition is d * d <= b.

For a large interval (for example up to 107) the Sieve of Eratosthenes is faster.

Solution (C++)

#include <iostream>
using namespace std;

bool prost(long long b) {
    if (b < 2) return false;              // 0 and 1 are not prime
    for (long long d = 2; d * d <= b; d++) // it is enough to check divisors up to the square root
        if (b % d == 0) return false;
    return true;
}

int main() {
    long long a, b;
    cin >> a >> b;
    int c = 0;                            // number of primes printed
    for (long long i = a; i <= b; i++) {
        if (prost(i)) {
            cout << i;
            c++;
            cout << (c % 10 == 0 ? "\n" : " ");   // 10 per line
        }
    }
    if (c % 10 != 0) cout << "\n";
    return 0;
}
Fixes compared with the old version: the old function declared 1 a prime and checked all divisors up to the number itself (slow for large numbers).