Could i <= n / i be wrong in some cases because of division?

Правка en1, от Destopia, 2022-04-08 23:55:08

Let's say I want to check whether an integer is prime or not.

Implementation $$$1$$$:

bool is_prime1(long long n) {
    if (n < 2)
        return false;
    for (long long i = 2; i * i <= n; i++) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}

Implementation $$$2$$$:

bool is_prime2(long long n) {
    if (n < 2)
        return false;
    for (long long i = 2; i <= n / i; i++) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}

Which implementation is better?

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en1 Английский Destopia 2022-04-08 23:55:08 668 Initial revision (published)