import java.util.Scanner;
public class SimpRad
{
static int[] simplify( int square )
{
double outside = 1;
double inside = square;
int[] simplified = { 1, square };
// Check if it's already a perfect square
outside = Math.sqrt(square);
if( outside == Math.floor(outside) )
{
simplified[0] = (int)outside;
simplified[1] = 1;
return simplified;
}
// Check if it simplifies
for( int i = (square - 1); i > 1; i-- )
{
inside = (double)square / i;
// Is the counter a factor?
if( inside == Math.floor(inside) )
{
// Is the square divided by the factor a perfect square?
outside = Math.sqrt(i);
if( outside == Math.floor(outside) )
{
simplified[0] = (int)outside;
simplified[1] = (int)inside;
return simplified;
}
}
}
// Otherwise, since it hasn't simplified, return the original radical
return simplified;
}
public static void main( String[] args )
{
String arg;
Scanner user_input = new Scanner(System.in);
int radicand = -1;
final String SQUARE_ROOT_SYMBOL = "\u221A";
int[] rads;
String i = "";
String negative = "";
try {
arg = args[0];
radicand = Integer.parseInt(arg);
} catch( ArrayIndexOutOfBoundsException e ) {
arg = "";
} catch( NumberFormatException e2 ) {
arg = "";
}
while( radicand < 0 )
{
System.out.print("Please enter the current radicand: ");
arg = user_input.next();
try {
radicand = Integer.parseInt(arg);
} catch( NumberFormatException e ) {
System.out.print("That's not an integer! ");
continue;
}
if( radicand < 0 )
{
i = "i";
negative = "-";
radicand = -radicand;
}
}
rads = simplify(radicand);
// If it's already simplified
if( rads[0] == 1 )
{
System.out.println(SQUARE_ROOT_SYMBOL + negative + radicand + " = " + i
+ SQUARE_ROOT_SYMBOL + rads[1]);
}
// If it's a perfect square
else if( rads[1] == 1 )
{
System.out.println(SQUARE_ROOT_SYMBOL + negative + radicand + " = " + rads[0] + i);
}
else
{
System.out.println(SQUARE_ROOT_SYMBOL + negative + radicand + " = " + rads[0] + i
+ SQUARE_ROOT_SYMBOL + rads[1]);
}
}
}
Comments