首页 > 解决方案 > 如何使这个应用程序因子成为具有二次公式或其他技巧的多项式?

问题描述

如何使这个应用程序因子成为具有二次公式或其他技巧的多项式?

多项式3x^2 +10x -8可以使用 分组X 技巧分解为(x +4)(3x -2)。我希望我的代码能够做到这一点,但我不知道如何完成它。我的代码将多项式分解为(x -0.6666666666666666)(x +4.0) ,这不是我想要的。此代码段

require "option_parser"


puts "Please enter your variable values assuming the form ax**2 + bx + c ."

puts "a: "
a = gets
exit if a.nil? 
a = a.to_i 

puts "b: "
b = gets
exit if b.nil? 
b = b.to_i

puts "c: "
c = gets
exit if c.nil? 
c = c.to_i

the_gcd = a.gcd(b).gcd(a.gcd(c))

if the_gcd != 1

  x1 = (-1*b + (b**2 - 4*a*c) ** 0.5)/(2 * a)
  x2 = (-1*b - (b**2 - 4*a*c) ** 0.5)/(2 * a)

  if x1.to_i - x1 != 0 || x2.to_i - x2 != 0
    puts "The root is not a whole number. Consider grouping for factoring the polynomial."
    if x1 < 0 && x2 < 0
      puts "#{the_gcd}(x +#{-x1})(x +#{-x2})"
    elsif x1 < 0 && x2 > 0
      puts "#{the_gcd}(x +#{-x1})(x #{-x2})"
    elsif x1 > 0 && x2 < 0
      puts "#{the_gcd}(x #{-x1})(x +#{-x2})"
    elsif x1 > 0 && x2 > 0
      puts "#{the_gcd}(x #{-x1})(x #{-x2})"
    end    
    exit
  
  else
    if x1 < 0 && x2 < 0
      puts "#{the_gcd}(x +#{-x1.to_i})(x +#{-x2.to_i})"
      exit
    elsif x1 < 0 && x2 > 0
      puts "#{the_gcd}(x +#{-x1.to_i})(x #{-x2.to_i})"
      exit
    elsif x1 > 0 && x2 < 0
      puts "#{the_gcd}(x #{-x1.to_i})(x +#{-x2.to_i})"
      exit
    elsif x1 > 0 && x2 > 0
      puts "#{the_gcd}(x #{-x1.to_i})(x #{-x2.to_i})"
      exit
    end    
  end
   
  
  
  if (b**2 - 4*a*c) < 0
    puts "No real solution. Imaginary numbers involved in the solution."
    exit
  end

end

#The part below does not utilize GCD

x1 = (-1*b + (b**2 - 4*a*c) ** 0.5)/(2 * a)
x2 = (-1*b - (b**2 - 4*a*c) ** 0.5)/(2 * a)

if x1.to_i - x1 != 0 || x2.to_i - x2 != 0
  puts "The root is not a whole number. Consider grouping for factoring the polynomial."
  if x1 < 0 && x2 < 0
    puts "(x +#{-x1})(x +#{-x2})"
  elsif x1 < 0 && x2 > 0
    puts "(x +#{-x1})(x #{-x2})"
  elsif x1 > 0 && x2 < 0
    puts "(x #{-x1})(x +#{-x2})"
  elsif x1 > 0 && x2 > 0
    puts "(x #{-x1})(x #{-x2})"
  end    
  exit

else
  if x1 < 0 && x2 < 0
    puts "(x +#{-x1.to_i})(x +#{-x2.to_i})"
  elsif x1 < 0 && x2 > 0
    puts "(x +#{-x1.to_i})(x #{-x2.to_i})"
  elsif x1 > 0 && x2 < 0
    puts "(x #{-x1.to_i})(x +#{-x2.to_i})"
  elsif x1 > 0 && x2 > 0
    puts "(x #{-x1.to_i})(x #{-x2.to_i})"
  end    
end
   
if (b**2 - 4*a*c) < 0
    puts "No real solution. Imaginary numbers involved in the solution."
    exit
  end

一个更大的应用程序的一部分,该应用程序也处理二次多项式的其他因式分解方法 。让这些其他因式分解方法,例如完美平方三项式分解或完美平方差,不在这个问题的范围内。我在这个 Python 代码中遇到了一个类似的问题,显然是通过使用分数来解决的。可以利用 Crystal 中的分数来解决我的问题吗?

标签: polynomialsalgebracrystal-langquadratic-curve

解决方案


推荐阅读