[PYTHON] Let's create an automatic factorization device / Junior High School Mathematics Vol.1

Can it be factored using programming?

** * Welcome if there is any improvement, so thank you. ** **

After studying, I started thinking about making an automatic factorization device, but the source code is not beautiful. .. .. Although it is full of feelings in some places, a source that can be factorized at the basic mathematics level of junior high school has been completed.

It may be better to factorize from the factor theorem. I'm in trouble if I get a lot of fractions, so I wonder if I have to do it steadily.

If you use the following source code, your computer will do it for you at the junior high school math level, so your homework may be faster! ??

I hope that the following factorization can be done. STEP1 doesn't seem to take much time, but I'm tired today, so I went to junior high school math.

STEP1 : (a+c)x**2 + (ad+bc)x + bd = (ax+b)(cx+d) STEP2: Factorization of cubic equation using factor theorem STEP3: Comprehensively cover other university entrance exams

If you pass the input value to the code below, the factorization formula will be output.

[Input rules] ① Leave a space between the sign and the formula (2) In the case of 1 * x, 1 is usually omitted, but it is described as 1x.

(Example) input x**2 - 20x + 96 output (x - 12)(x - 8)

input x**2 - 9 output (x + 3)(x - 3)

input x**2 - 4x + 4 output (x - 2)**2


import math

a = 0
b = 0
jud1 = "+"
jud2 = "+"

nums = input().split()

if len(nums) <= 3:
    a = int(math.sqrt(int(nums[2])))
    print("(x + " + str(a) + ")(x - " + str(a) + ")")
else:
    if nums[3] == "-":
        nums[4] = int(nums[4])*(-1)
    
    li = list(nums[2].split("x"))
    
    if nums[1] == "-":
        li[0] = int(li[0])*(-1)

    for i in range(-100,100):
        if (i * (int(li[0]) - i)) == int(nums[4]):
            a = i
            b = int(li[0]) - i
    
    if a < 0:
        jud1 = "-"
        
    if b < 0:
        jud2 = "-"
    
    if a == b:
        print("(x " + jud1 , str(abs(a)) + ")**2")
    else:
        print("(X " + jud1 , str(abs(a)) + ")(x " + jud2 , str(abs(b)) + ")")

Points to improve

Since it is a beginner, there may be a simple way to find it, but I think it would be smarter if I could easily extract the coefficients of each term (preferably including the code) **. Also, forcibly create a pattern with only two terms, such as x ** 2 -9.

if len(nums) <= 3:
    a = int(math.sqrt(int(nums[2])))
    print("(x + " + str(a) + ")(x - " + str(a) + ")")

It is the most unpleasant place to say. I've been able to pass it so far, but I'm wondering what to do because I'm in trouble when something like hey x ** 3 -8 comes out.

Recommended Posts

Let's create an automatic factorization device / Junior High School Mathematics Vol.1
Junior high school committee
[High school mathematics + python] Logarithmic problem
Junior high school committee (NetworkX version)