Блог пользователя Destopia

Автор Destopia, история, 4 года назад, По-английски

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?

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

»
4 года назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

I mean, they look pretty similar to me, and they are both correct. (the second implementation won't be wrong because the only case it could have problems with is when n is a square, and the <= will take care of that)

»
4 года назад, скрыть # |
 
Проголосовать: нравится -16 Проголосовать: не нравится

I checked the following implementations on multiple test cases but I couldn't find any sort of TLEs in my code. Maybe it doesn't matter too much whether you use the first implementation or the second implementation. I think both of them will work fine. Obviously these are brute-force approaches, you can't use them in problems with very big constraints like 2e18 or so. You'll have to use techniques like Sieve of Eratosthenes to counter such problems.

»
4 года назад, скрыть # |
 
Проголосовать: нравится +30 Проголосовать: не нравится

FWIW * operator is faster than / operator, so first implementation has lower constant

  • »
    »
    4 года назад, скрыть # ^ |
     
    Проголосовать: нравится +16 Проголосовать: не нравится

    No! Calculating n / i is free, because the loop body is already calculating n % i, and a decent compiler is smart enough to share them. They both take exactly the same amount of time because they are limited by the poor throughput of the 64-bit div/mod CPU instruction.