polynomials - 如何使这个应用程序因子成为具有二次公式或其他技巧的多项式?
问题描述
如何使这个应用程序因子成为具有二次公式或其他技巧的多项式?
多项式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 中的分数来解决我的问题吗?
解决方案
推荐阅读
- app-store - 错误 ITMS-90164:“com.apple.developer.ubiquity-kvstore-identifier”密钥的代码签名权利无效
- php - 如何在视图中分离 RepeatedType 小部件?
- ionic-framework - 关闭浏览器后 ionic InAppBrowser 请求未经授权
- swift - SCNNode SCNAction.move(to:) 未运行但被调用 - Swift
- amazon-web-services - 如何为域和子域安装 SSL 证书
- celery - Django/Celery:max_retries 用于重试,但打印值始终是 Celery 默认值 (3)
- python - 如何使用熊猫更改转置数据框的布局
- java - Gradle bootrun 使用 openjdk 11 失败
- java - 由于 Kotlin 中未解析的引用,无法设置文本或可绘制对象
- slack - 松弛螺栓清除视图堆栈