Challenge: Difference and Product

Subdomeniu: Algebra (algebra)

Scor cont: 20.0 / 20

Submission status: Accepted

Submission score: 1.0

Submission ID: 464739430

Limbaj: python3

Link challenge: https://www.hackerrank.com/challenges/difference-and-product/problem

Cerinta

Tim likes Math. He likes it so much that he always brings his tablets with him and reads math e-books everywhere, even during parties.

Tim found an interesting exercise in one of the e-books he is reading. But you want him to join the party, so you decide to answer the question for him.

The problem is: Given $D$ and $P$, how many ordered pairs of integers are there whose [absolute difference](http://en.wikipedia.org/wiki/Absolute_difference) is $D$ and whose product is $P$? In other words, how many pairs of integers $(A,B)$ are there such that:

$$|A-B| = D$$
$$A\times B = P$$

Input Format

The first line of input contains $T$, the number of test cases. The next $T$ lines describe the test cases.

Each test case consists of a single line containing two integers $D$ and $P$ separated by a single space.

Output Format

For each test case, output a single line containing a single integer which is the answer for that test case.

**Constraints**  

$1 \le T \le 20000$  
$|D| \le 10^9$  
$|P| \le 10^9$

Cod sursa

import sys
import math

def count_pairs(d, p):
    # HackerRank tests include negative D and expect 0 for them.
    if d < 0:
        return 0
    delta = d * d + 4 * p
    if delta < 0:
        return 0
    s = math.isqrt(delta)
    if s * s != delta:
        return 0

    pairs = set()
    for sd in (d, -d):
        for num in (sd + s, sd - s):
            if num % 2 != 0:
                continue
            a = num // 2
            b = a - sd
            if a * b == p and abs(a - b) == d:
                pairs.add((a, b))
    return len(pairs)

def main():
    data = sys.stdin.read().strip().split()
    if not data:
        return
    t = int(data[0])
    out = []
    i = 1
    for _ in range(t):
        d = int(data[i]); p = int(data[i + 1]); i += 2
        out.append(str(count_pairs(d, p)))
    sys.stdout.write('\n'.join(out))

if __name__ == '__main__':
    main()
HackerRank Algebra – Difference and Product