Program to find coefficients of linear equations that has only one solution in Python

Suppose we have a value n, we have to find the number of pairs (a, b) [a

So, if the input is like n = 4, then the output will be 2 because the valid pairs are (1, 2) and (1, 3).

To solve this, we will follow these steps −

  • Define a function divisors_gen() . This will take n
  • divs := a list of lists of size n+1. And each inner list is holding 1
  • divs[0] := a list with only one element 0
  • for i in range 2 to n, do
    • for j in range 1 to floor of (n / i) + 1, do
      • insert i at the end of list at index [i * j]
  • return divs but reverse all internal lists
  • From the main method, do the following −
  • result := 0
  • d_cache := divisors_gen(n+1)
  • for a in range 1 to n - 1, do
    • i := 1
    • s := a new set
    • while a*i
    • b := n - a*i
    • for each d in d_cache[b], do
      • if d > a, then
        • if d not in s, then
          • result := result + 1
      • otherwise,
        • come out from the loop
      • insert d into the set s
    • i := i + 1
  • return result
  • Example

    Let us see the following implementation to get better understanding −

    def divisors_gen(n):
       divs = [[1] for x in range(0, n + 1)]
       divs[0] = [0]
       for i in range(2, n + 1):
          for j in range(1, n // i + 1):
             divs[i * j].append(i)
       return [i[::-1] for i in divs]
    
    def solve(n):
       result = 0
       d_cache = divisors_gen(n+1)
    
       for a in range(1, n):
          i = 1
          s = set([])
          while a*i  a:
                   if d not in s:
                      result += 1
                else:
                   break
                s.add(d)
             i += 1
       return result
    
    n = 4
    print(solve(n))

    Input

    4
    

    Output

    2
    Updated on: 2021-10-25T08:11:57+05:30

    559 Views

    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements