Editorial for CKPRIME


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.

Submitting an official solution before solving the problem yourself is a bannable offence.

\(\color{red}{\text{Spoiler Alert}_{{}_{{}^{{}^{v2.0}}}}}\)

\(\color{red}{\text{Khuyến khích bạn đọc trước khi đọc phần lời giải xin hãy thử code ra thuật của mình dù nó có sai hay đúng}}\)

\(\color{red}{\text{Sau đó từ phần bài giải và thuật toán trước đó mà đối chiếu, rút nhận xét với thuật của mình và thu được bài học (không lãng phí thời gian đâu).}}\)



\(\color{orange}{\text{Hint 1 <Brute-force>}}\)

  • Gọi \(p = a^2 - b^2\), kiểm tra nếu \(p\) là nguyên tố thì in "YES" ngược lại in "NO"

\(\color{orange}{\text{Hint 2 <Math>}}\)

  • \(p\) là số nguyên tó khi \(p\) có 2 ước nguyên dương duy nhất là \(1\)\(p\)

\(p = a^2 - b^2 = (a - b) \times (a + b)\)\(a + b > a - b\)

Nên \(p\) nguyên tố \(\Leftrightarrow pair(a - b, a + b) = pair(1, p)\)


\(\color{green}{\text{Preference AC Code }}\): Math

\(^{^{\color{purple}{\text{Complexity : }} O(\sqrt{a + b})\ \color{purple}{\text{time}}\ ||\ O(1)\ \color{purple}{\text{memory}}}}\)

C++
bool isPrime(ll p)
{
    if (p < 2) return false;
    if (p < 4) return true;
    if (!(p & 1) || p % 3 == 0) return false;

    int lim = sqrt(p);
    for (int x = 5; x <= lim; x += 6)
        if (p % x == 0 || p % (x + 2) == 0)
            return false;

    return true;
}

int main()
{
    ll a, b;
    cin >> a >> b; 

    if (a - b != 1)
    {
        cout << "NO";
        return 0;
    }

    cout << (isPrime(a + b) ? "YES" : "NO");
    return 0;
}


Comments

There are no comments at the moment.