gtlsgamr / codingproblems

A website for sharing and answering for coding questions. (usually problems that are asked in interviews and stuff)
GNU General Public License v3.0
0 stars 0 forks source link

https://codingproblems.netlify.app/post/linear_solution/ #2

Open utterances-bot opened 3 years ago

utterances-bot commented 3 years ago

Coding Problems | Linear equation solution

Given a linear equation of n variables...

https://codingproblems.netlify.app/post/linear_solution/

pystardust commented 3 years ago

python3

#!/bin/python3

coeff = [ 2, 2, 3 ]
rhs = 4

# the values can't go negative, so we can try to iterate over each term and try
# figuring out the linear equation in the remaining terms (1 less term)
# if there is only one term, check divisibility and return 1 and 0 respectively

def get_sol_num(coeff: list[int], rhs: int) -> int:
    term_coeff = coeff[0]
    # when only a single term is coeffs, then check divisibility
    if len(coeff) == 1:
        if rhs % coeff[0] == 0:
            return 1
        else:
            return 0

    term = 0
    count = 0
    # when more then one term then, recursively call and add the counts for
    # each value this term can take without going negative
    while (rhs - term_coeff * term) >= 0:
        count+=get_sol_num(coeff[1:], rhs - term_coeff * term)
        term+=1
    return count

if __name__ == '__main__':
    print(get_sol_num(coeff,rhs))