Home > Python >Python Exercise: Integer Solutions Of Equation

Integer Solutions Of Equation

Given equation x + y + z = n where n is a positive integer number that user can input, write a program to print out all possible solutions (x, y, z) such that x, y, and z all are positive integer and the total number of the solutions.

Example:
n = 3
(1, 1, 1) is the only solution

n = 4:
(1, 1, 2), (1, 2, 1), (2, 1, 1) , total solutions = 3

You need login to comment

Solution submitted by Dzeng at April 9, 2020, 11:52 p.m.
def solution1(): #change n for different numbers n = 0 x = 1 y = 1 z = 1 set1 = [] solutions = [] count = 0 finished = False while finished == False: if x + y + z == n: count += 1 set1 = [x, y, z] solutions.append(set1) if y < (n-1) and z > 1: y += 1 z -= 1 elif x < n-2: x += 1 y = 1 z = 1 else: finished = True else: z += 1 print("There are", count, "solutions, and the solutions are", solutions) #solution1() def equation_2(n): count = 0 ret =list() for x in range(1, n): ret.append((x, n-x)) count +=1 return (count, ret) def main(): n = int(input("Enter Number:")) count = 0 solutions =list() for x in range(1, n-1): sol = equation_2(n-x) count += sol[0] for a in sol[1]: solutions.append((x, a[0], a[1])) print("There are", count, "solutions, and the solutions are", solutions) #main() def solution2(n): return [(x,y,z) for x in range(1, n-1) for y in range(1, n-x+1) for z in range(1,n-x-y+1) if x+y+z == n] #print(len(solution2(30)))

You need login to submit your solution