Home > Net >  write a python code to find the three numbers x , y and z . whose sum and product is given by the us
write a python code to find the three numbers x , y and z . whose sum and product is given by the us

Time:01-13

I have this question, that can we write a python code for determining x,y,z whose sum and product are given by the user. that it can return three numbers whose sum and product are inputs. for example... 3 3 5 = 11 and 3x3x5=45, so when I give the computer 11 and 45 it returns 3,3,5. I want to know is there a way to do it.

CodePudding user response:

The caveman approach (brute force with a miniscule amount of dynamic programming). MiTriPy's answer generalizes to n variables, although probably isn't more performant.

def solve(eqsum, eqprod):
    solution_count = 0
    for x in range(0, eqsum 1):
        for y in range(0, eqsum 1-x):
            for z in range(0, eqsum 1-x-y):
                if x y z == eqsum:
                    if x*y*z == eqprod:
                        print(f"x={x} y={y} z={z}")
                        solution_count  = 1
    print(f"Found {solution_count} solutions.");

solve(eqsum=11, eqprod=45)

CodePudding user response:

Made something fast and very clumsy:

import itertools
from numpy import prod

def find_subset_of_numbers(number, product):
    subset_of_numbers = [x for x in range(1, number   1)]
    for x in range(1, number 1):
        subset_of_numbers.append(x)
    for x in range(1, number 1):
        subset_of_numbers.append(x)

    result = [seq for i in range(3, 0, -1)
      for seq in itertools.combinations(subset_of_numbers, i)
      if sum(seq) == number and len(seq) == 3 and prod(seq) == product]

    return result

This will not handle duplicates very well but you could add another check for that:

print(find_subset_of_numbers(11, 45))
output: [(3, 5, 3), (3, 5, 3), (3, 3, 5), (3, 3, 5), (3, 5, 3), (3, 3, 5), (5, 3, 3), (3, 5, 3), (3, 3, 5)]

CodePudding user response:

Here is a fairly efficient solution.

from collections.abc import Iterator
from math import sqrt


def solve(target_sum: int, target_prod: int) -> Iterator[tuple[int, int, int]]:
    for x in range(1, target_sum):
        if target_prod % x:
            continue
        rest_sum = target_sum - x
        try:
            desc = sqrt(rest_sum ** 2 - 4 * (target_prod // x))
        except ValueError:
            continue
        if desc.is_integer():
            yield (x, rest_sum   int(desc), rest_sum - int(desc))
            yield (x, rest_sum - int(desc), rest_sum   int(desc))

It uses the fact that if x y = s and xy = p, then {x, y} = {s ± √(s² − 4 p)}.

  •  Tags:  
  • Related