Modules - Structured Programming 2
Teacher’s Notes:
========================================================================
This is a very challenging problem for new programmers.
There are many ways to solve this problem.
Assignment:
========================================================================
Find the Factors
A basic quadratic equation can be expressed an the form Ax² + Bx + C. The factors of the equation are the values of x that would result in the equation evaluating to 0. For this problem, we will always assume that the value of A will be 1.
You may **NOT** use the general solution equation for quadratic equations in your solution (x = [−b ± √(b2 − 4ac)]/2a) to find your solution.
Write a program that reads two integers from the keyboard to represent the values of B and C respectively. Then output the factored version of the equation to the screen.
Note: All solutions in this problem will be integer solutions.
Sample Input 1
7
12
### Sample Output 1
(x+3)
(x+4)
### Sample Input 2
-6
-27
### Sample Output 2
(x-9)
(x+3)
Solution (JAVA):
========================================================================
import java.util.Scanner;
class Main{
public static void main(String[] args) {
int b = 0, c = 0;
Scanner input = new Scanner(System.in);
b = input.nextInt();
c = input.nextInt();
int copyOfC = c;
if (c < 0)
copyOfC = -1*c;
if(b == 0 && c == 0){
System.out.println("(x+0" + ")");
System.out.println("(x+0" + ")");
}
for(int x = 1; x <= copyOfC; x++){
if(c%x == 0){
if(c < 0){
if(c/x + x == b && c/x < x)
{
System.out.println("(x" + c/x + ")");
System.out.println("(x+" + x + ")");
}
else if (-1*c/x - x == b && c/x > x)
{
System.out.println("(x+" + c/x + ")");
System.out.println("(x" + x + ")");
}
}
else if (c > 0){
if(b > 0){
if(c/x + x == b){
System.out.println("(x+" + c/x + ")");
System.out.println("(x+" + x + ")");
break;
}
}
else if(b < 0){
if(-1*c/x - x == b)
{
System.out.println("(x-" + c/x + ")");
System.out.println("(x-" + x + ")");
break;
}
}
}
}
}
}
}