Soluție HackerRank pentru Count Solutions, subdomeniul Algebra, în Python 3. Include cerința formatată, exemple, explicația pașilor și cod sursă.

  • Problemă: Count Solutions
  • Domeniu: Algebra
  • Limbaj: Python 3

Challenge: Count Solutions

Subdomeniu: Algebra (algebra)

Scor cont: 40.0 / 40

Submission status: Accepted

Submission score: 1.0

Submission ID: 464740537

Limbaj: python3

Link challenge: https://www.hackerrank.com/challenges/count-solutions/problem

Cerință

Eric has four integers a, b, c, and d.

Instantly, he wondered how many pairs of integers, (x, y), satisfy the following equation:

x^2 + y^2 = (x × a) + (y × b)

where 1 ≤ x ≤ c and 1 ≤ y ≤ d.

Find and print the number of pairs that satisfy the above equation.

Input Format

The first line contains an integer q, the number of queries.
q lines follow, each containing four integers, a, b, c, and d, in that order.

Output Format

For each test case, print one line, the number of pairs (x,y) that are valid solutions to Eric's equation.

Constraints

+ 1 ≤ q ≤ 10
+ 1 ≤ a,b,c,d ≤ 10^5

Cod sursă

import sys
import math

def count_query(a, b, c, d):
    ans = 0
    b2 = b * b
    for x in range(1, c + 1):
        disc = b2 + 4 * x * (a - x)
        if disc < 0:
            continue
        s = math.isqrt(disc)
        if s * s != disc:
            continue
        # y = (b ± s) / 2
        if (b + s) % 2 == 0:
            y1 = (b + s) // 2
            if 1 <= y1 <= d:
                ans += 1
        if s != 0 and (b - s) % 2 == 0:
            y2 = (b - s) // 2
            if 1 <= y2 <= d:
                ans += 1
    return ans

def main():
    data = sys.stdin.buffer.read().split()
    if not data:
        return
    q = int(data[0])
    out = []
    idx = 1
    for _ in range(q):
        a = int(data[idx]); b = int(data[idx + 1]); c = int(data[idx + 2]); d = int(data[idx + 3]); idx += 4
        out.append(str(count_query(a, b, c, d)))
    sys.stdout.write('\n'.join(out))

if __name__ == '__main__':
    main()
HackerRank Algebra – Count Solutions