brainfrz icon

Simplifying Radicals in Java

brainfrz | PRO | 09/12/15 09:14:56 PM UTC | 0 ⭐ | 789 👁️ | Never ⏰ | []
Java |

2.35 KB

|

None

|

0 👍

/

0 👎

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;
 
        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 )
            {
                System.out.print("That's a negative. ");
            }
        }
 
        rads = simplify(radicand);
        System.out.println(SQUARE_ROOT_SYMBOL + radicand + " = " + rads[0] + SQUARE_ROOT_SYMBOL +
                                rads[1]);
    }
}

Comments