Creating a Complex number class in Java - java

I am a new in java and programming in general.
I am currently doing complex numbers. I know that there might be an answer for this online, but it will also reveal if I used the correct algorithm and so on, so I am trying to avoid other answers around here.
My main issue is that I am having trouble with the Divide class that I made, since in complex number division we are going to return a fraction as an answer, I can't figure out how to have the program return the 2 statements that it calculate, can someone advise what can be done? Here is the part of the division code, it works fine when I check both part 1 and then part 2, but how can i get it to return both of them when calling using that class.
I attached my full code that I made, I know it can be tweaked to have less coding, but that is not my current concern.
Thanks for your help in advance.
class complexN {
int R, I;
complexN(int R, int I) {
this.R = R;
this.I = I;
}
complexN AddCN(complexN A) {
return new complexN(this.R + A.R, this.I + A.I);
}
complexN SubCN(complexN A) {
int AnsR = this.R - A.R;
int AnsI = this.I - A.I;
complexN Sum = new complexN(AnsR, AnsI);
return Sum;
}
complexN MulCN(complexN A) {
int AnsI = (this.R * A.I) + (this.I * A.R);
int AnsR = (this.R * A.R) - (this.I * A.I);
complexN Sum = new complexN(AnsR, AnsI);
return Sum;
}
complexN DivCN(complexN A) {
complexN ComCon = new complexN(A.R, (A.I * -1));
complexN part1 = new complexN(this.R, this.I).MulCN(ComCon);
complexN part2 = A.MulCN(ComCon);
return part1;
}
void print() {
String i = (this.I == 1 ? "" : (this.I == -1 ? "-" : "" + this.I));
if (this.R != 0 && this.I > 0) {
System.out.println(this.R + "+" + i + "i");
}
if (this.R != 0 && this.I < 0) {
System.out.println(this.R + i + "i");
}
if (this.R != 0 && this.I == 0) {
System.out.println(this.R);
}
if (this.R == 0 && this.I != 0) {
System.out.println(i + "i");
}
if (this.R == 0 && this.I == 0) {
System.out.println("0");
}
}
}
class complex {
public static void main(String[] args) {
// TODO Auto-generated method stub
complexN z1 = new complexN(5, 2);
complexN z2 = new complexN(3, -4);
System.out.print("z1 = ");
z1.print();
System.out.print("z2 = ");
z2.print();
System.out.println("---------");
z1.DivCN(z2).print();
}
}

Related

Prime factorization using GUI (swing/awt)

This code uses Swing and awt to compute prime factorization, the code works, but it shows only one prime factor, for example: if i compute 56 the answer is just 7, how can i fix it?
thanks in advance
calculate6.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Get values from text fields
try {
int a = Integer.parseInt(input1.getText());
result.setText(String.valueOf(a + " "));
for (int i = 2; i <= a; i++) {
while (a % i == 0) {
result.setText(String.valueOf(i + " "));
// System.out.println(i + " ");
a = a / i;
}
}
if (a < 1)
result.setText(String.valueOf(a + " "));
// System.out.println(a + " ");
}
catch (Exception f) {
JOptionPane.showMessageDialog(rootPane, "ERROR: " + (f.getMessage()));
}
String aField = input1.getText();
if (e.getSource() == calculate6) {
if ("".equals(aField)) {
String emptyFieldWarning;
emptyFieldWarning = "One field is empty!";
JOptionPane.showMessageDialog(rootPane, emptyFieldWarning);
}
}
}
});
Edit 1: i have changed the operation part
Your Swing part is fine. If you just try to execute
int a = 56;
for(int i = 2; i< a; i++) {
while (a % i == 0) {
a = a / i;
}
}
System.out.println(a);
you get 7,so the problem is in this part, you shoul look over here
Problem is in the while loop. It is not accumulating the factors. Try this getPrimeFactors() in this sample program.
import java.util.*;
public class PrimeFactors {
public static void main(String[] args) {
System.out.println("56 -> " + PrimeFactors.getPrimeFactors(56));
System.out.println("30 -> " + PrimeFactors.getPrimeFactors(30));
System.out.println("154 -> " + PrimeFactors.getPrimeFactors(154));
}
public static List<Integer> getPrimeFactors(int input) {
List<Integer> factors = new ArrayList<>();
for (int i = 2; i <= input; i++) {
while (input%i == 0) {
input = input/i;
factors.add(i);
}
}
return factors;
}
}
public static final IntFunction<String> getPrimeFactorsAsString = num -> {
List<Integer> res = new ArrayList<>();
for (int i = 2, sqrt = (int)Math.sqrt(num); i <= sqrt; i++) {
while (num % i == 0) {
res.add(i);
num /= i;
}
}
return res.stream().map(String::valueOf).collect(Collectors.joining(" "));
};
Demo
System.out.println(getPrimeFactorsAsString.apply(56)); // 2 2 2 7
System.out.println(getPrimeFactorsAsString.apply(660)); // 2 2 3 5 11

How to pass a String parameter to a void method? [duplicate]

This question already has an answer here:
What does "Incompatible types: void cannot be converted to ..." mean?
(1 answer)
Closed 3 years ago.
I need to write a Java program for a course I'm taking which looks for genes in a strand of DNA.The Issue I am having is that from the test method, I need to pass printAllgenes(a) to the void printAllgenes method. In the test method I've tried setting 'int a' to 'String a', but in either case an error when compiling explaining that void cannot be converted to int or String. I'm sure its obvious, but I'm very new to programming, so please pardon my ignorance! Thank you.
import java.io.*;
import edu.duke.*;
public class FindProtein {
public void test() {
String a = "atg aaa tab tag atg aaa tga aat ag";
int b = printAllgenes(a);
System.out.println("DNA string is " + a);
System.out.println("Gene found is " + b);
}
public void printAllgenes(String dna) {
int sp = 0; //start point
while (true) {
int start = dna.indexOf("atg,sp");
if (start == -1) {
break;
}
int stop = findStopIndex(dna, start + 3);
if (stop != dna.length()) {
System.out.println(dna.substring(start, stop + 3));
sp = stop + 3;
} else {
sp = sp + 3;
}
}
}
public int findStopIndex(String dna, int index) {
int tga = dna.indexOf("tga", index);
if (tga == -1 || (tga - index) % 3 != 0) {
tga = dna.length();
}
int taa = dna.indexOf("taa", index);
if (taa == -1 || (taa - index) % 3 != 0) {
taa = dna.length();
}
int tag = dna.indexOf("tag", index);
if (tag == -1 || (tga - index) % 3 != 0) {
tag = dna.length();
}
return Math.min(tga, Math.min(taa, tag));
}
}
Try to use just:
printAllgenes(a);
Because printAllgenes method doesn't have any type of return statement.
change return type void to int It will return your count whatever u want to return from printAllgenes(String dns) Method. You will get a int return which will initialize you variable b that is being displayed on Console.
public int printAllgenes(String dna){
int sp = 0; //start point
while (true){
int start = dna.indexOf("atg,sp");
if (start==-1){
break;
}
int stop = findStopIndex(dna,start+3);
if (stop!=dna.length()){
System.out.println(dna.substring(start,stop+3));
sp=stop+3;
}
else{
sp=sp+3;
}
}
return sp;
}
Now Your Test Method Implementation will work fine...
public void test(){
String a= "atg aaa tab tag atg aaa tga aat ag";
int b = printAllgenes(a);
System.out.println("DNA string is " +a);
System.out.println("Gene found is "+b);
}
Thank you..

Adding two linked lists together in java

Hello there,
My lab assignment is to take two strings, convert them into linkedLists and add the linked lists up. I have managed to get them to a level where they could be added together but you can't carryover. I have been working on that part and can't seem to figure it out.
The code is typed below. Thank you!
I reverse the strings when they get inputed in. the output string also needs to be reversed.
Code package linkedlist;
import java.util.Scanner;
/**
*
* #author Spock-II
*/
public class LinkedList {
public static LinkedInt Trueadd(LinkedInt A, LinkedInt B) {
LinkedInt a = A;
LinkedInt b = B;
int next;
LinkedInt sum = new LinkedInt();
System.out.println("Switches!");
if (a.size() > b.size()) {
System.out.println("size: " + (a.size() - b.size()));
int limit = a.size() - b.size();
for (int i = 0; i < limit; i++) {
b.addToLinkList("0", i);
System.out.println("inloop b");
System.out.println("i : " + i);
}
System.out.println("loop complete");
} else if (a.size() < b.size()) {
System.out.println("size: " + (b.size() - a.size()));
int limit = b.size() - a.size();
for (int i = 0; i < limit; i++) {
a.addToLinkList("0", i);
System.out.println("inloop b");
System.out.println("i : " + i);
}
System.out.println("loop complete");
}
System.out.println("Switch overcame");
int carryover = 0;
while (a.head != null & b.head != null) {
String[] carryCheck = (Integer.valueOf(a.head.getItem()) + Integer.valueOf(b.head.getItem()) + "").split("");
if (carryCheck.length == 2) {
sum.addToLinkList((Integer.valueOf(carryCheck[1])+carryover)+"", 0);
carryover = Integer.valueOf(carryCheck[0]);
} else {
int i = Integer.valueOf(a.head.getItem()) + Integer.valueOf(b.head.getItem());
sum.addToLinkList(i + "", 0);
}
System.out.println("a: " + a.head.getItem());
System.out.println("b: " + b.head.getItem());
a.head = a.head.getLink();
b.head = b.head.getLink();
}
System.out.println("Completed");
return sum;
}
public static LinkedInt subtract(LinkedInt a, LinkedInt b) {
a.combine();
b.combine();
LinkedInt difference = new LinkedInt(a.x - b.x);
difference.combine();
return difference;
}
public static LinkedInt multiply(LinkedInt a, LinkedInt b) {
a.combine();
b.combine();
LinkedInt product = new LinkedInt(a.x + b.x);
product.combine();
return product;
}
public static LinkedInt divide(LinkedInt a, LinkedInt b) {
a.combine();
b.combine();
LinkedInt sum = new LinkedInt(a.x + b.x);
sum.combine();
return sum;
}
public static LinkedInt modulus(LinkedInt a, LinkedInt b) {
a.combine();
b.combine();
LinkedInt rem = new LinkedInt(a.x + b.x);
rem.combine();
return rem;
}
public static void main(String[] args) {
// TODO code application logic here
Scanner i1 = new Scanner(System.in);
System.out.print("Please enter the first no. : ");
int a = i1.nextInt();
Scanner i2 = new Scanner(System.in);
System.out.print("Please enter the second no. : ");
int b = i2.nextInt();
System.out.println();
LinkedInt a1 = new LinkedInt(a);
LinkedInt a2 = new LinkedInt(b);
a1 = a1.populate();
a2 = a2.populate();
a1.combine();
a2.combine();
LinkedInt sum = Trueadd(a1, a2);
sum.combine2();
// LinkedInt sum = a1;
}
}
`
I don't know the exact structure of your LinkedInt class, but if it's a linkedList starting at the least significant digit, you should be able to do it change your loop to this:
int carryover = 0;
while (a.head != null & b.head != null) {
int sumDigits = Integer.parseInt(a.head.getItem()) + Integer.parseInt(b.head.getItem())+carryover;
// add least significant digit of sumDigits
sum.addToLinkList(Integer.toString(sumDigits % 10), 0);
// remove least significant digit from sumDigit to get the new carryover
carryover = sumDigits / 10;
a.head = a.head.getLink();
b.head = b.head.getLink();
}
if (carryover != 0) {
// if the last carryover isn't 0 add it as most significant digit of the result
sum.addToLinkList(Integer.toString(carryover), 0);
}
but in case you still want to convert between String and int as often as your code does, you need to add the carryover before converting to String[], not after converting:
while (a.head != null & b.head != null) {
// add carryover here
String[] carryCheck = (Integer.valueOf(a.head.getItem()) + Integer.valueOf(b.head.getItem()+carryover) + "").split("");
if (carryCheck.length == 2) {
// don't add carryover here
sum.addToLinkList((Integer.valueOf(carryCheck[1]))+"", 0);
carryover = Integer.valueOf(carryCheck[0]);
} else {
//...
}
// TODO: add carryover as most significant digit, if != 0

How do I avoid repetitiveness? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Im doing a tutorial in Java and I always read that I must try not to be repetitive and I noticed this is very repetitive; So if anyone can give me some tips to make it less repetitive or somehow better it is much appriciated. Thanks ;) (This isn't part of the the tutorial, I made it just for fun because of what I am learning in science at school)
Run.java file:
package scientificFormula;
public class Run {
public static void main(String[] args) {
Formula formula = new Formula();
formula.compound1 = args[0];
formula.compound2 = args[1];
String theFormula = formula.createFormula();
System.out.println("Molecule: " + args[0] + " " + args[1] + " = "
+ theFormula);
}
}
Formula.java file:
package scientificFormula;
import java.util.HashMap;
import java.util.Map;
public class Formula {
String compound1;
String compound2;
static private Map<String, String> map = new HashMap<String, String>();
static private void initiateIons() {
// 1+
map.put("Hydrogen", "H^1+");
map.put("Lithium", "Li^1+");
map.put("Sodium", "Na^1+");
map.put("Potassium", "K^1+");
map.put("Rubidium", "Rb^1+");
// 2+
map.put("Magnesium", "Mg^2+");
map.put("Calcium", "Ca^2+");
map.put("Strontium", "Sr^2+");
// 3+
map.put("Aluminium", "Al^3+");
// 3-
map.put("Nitrogem", "N^-3");
map.put("Phosphorus", "P^-3");
// 2-
map.put("Oxygen", "O^-2");
map.put("Sulfur", "S^-2");
map.put("Selenium", "Se^-2");
// 1-
map.put("Fluorine", "F^-1");
map.put("Chlorine", "Cl^-1");
map.put("Bromine", "Br^-1");
map.put("Iodine", "I^-1");
}
String createFormula() {
initiateIons();
// Example1: Input = Calcium Iodine:
// 2x + -1y = 0
// x = 1 and y = 2
// Output = CaI2
//
// Example2: Input = Sulfur Iodine
// Output = Molecule: Sulfur Iodine = SI2
String symbol1 = map.get(compound1);
String symbol2 = map.get(compound2);
int charge1 = Integer.parseInt(symbol1.replace("+", "").substring(
symbol1.length() - 2));
int charge2 = Integer.parseInt(symbol2.replace("+", "").substring(
symbol2.length() - 2));
String letter1 = null;
String letter2 = null;
if (symbol1.length() == 5) {
letter1 = symbol1.substring(0, 2);
} else if (symbol1.length() == 4) {
letter1 = symbol1.substring(0, 1);
}
if (symbol2.length() == 5) {
letter2 = symbol2.substring(0, 2);
} else if (symbol2.length() == 4) {
letter2 = symbol2.substring(0, 1);
}
int possitive1 = (int) Math.sqrt(charge1 * charge1);
int possitive2 = (int) Math.sqrt(charge2 * charge2);
if ((possitive1 == 1) & (possitive2 == 1)) {
return letter1 + letter2;
} else if (possitive1 == 1) {
return letter1 + possitive2 + letter2;
} else if (possitive2 == 1) {
return letter1 + letter2 + possitive1;
}
if (possitive1 == 0) {
possitive1 = -(charge1);
}
if (possitive2 == 0) {
possitive2 = -(charge2);
}
return letter1 + possitive2 + letter2 + possitive1;
}
}
I highly recommend reading the book clean code which mainly deals with refactoring.
Duplicating code is just one (important) issue when you start refactoring (also called DRY - Don't Repeat Yourself). There are many other principles and I'll try describe a few of them which I find most important:
One important "rule of thumb" is the SRP: Single Responsibility Principle, which says that each class should have only one responsibility, and if we apply the same idea to methods - each method should do only one thing! It might sound very strict, but when you'll start applying it - your code will become clearer to read and easier to maintain.
Another one is using meaningful names (classes/methods/variables):
return letter1 + possitive2 + letter2; // you probably meant positive with one 's' (typo!)
might mean something to you - but it will not mean much to another reader - now, of course you can solve it by adding code comments, but that's patching the problem instead of solving it. Further, code comments get stale - either become irrelevant or even worse - might mislead the reader when the code changes and the comment doesn't.
And last (for now), keep clear order of execution, let's take a piece of code that you posted and improve it:
String symbol1 = map.get(compound1);
String symbol2 = map.get(compound2);
int charge1 = Integer.parseInt(symbol1.replace("+", "").substring(
symbol1.length() - 2));
int charge2 = Integer.parseInt(symbol2.replace("+", "").substring(
symbol2.length() - 2));
String letter1 = null;
String letter2 = null;
if (symbol1.length() == 5) {
letter1 = symbol1.substring(0, 2);
} else if (symbol1.length() == 4) {
letter1 = symbol1.substring(0, 1);
}
if (symbol2.length() == 5) {
letter2 = symbol2.substring(0, 2);
} else if (symbol2.length() == 4) {
letter2 = symbol2.substring(0, 1);
}
int possitive1 = (int) Math.sqrt(charge1 * charge1);
int possitive2 = (int) Math.sqrt(charge2 * charge2);
As we can see: positive depends on charge which depends on symbol which depends on compound. And totaly unrelated to it: letter depends on symbol which depends on compound.
let's split it to separate methods:
int getPositive(String compound) { // I have no idea what "positive", "symbol" and compound represent, consider better names please
String symbol = map.get(compound);
int charge = Integer.parseInt(symbol.replace("+", "").substring(
symbol.length() - 2));
return (int) Math.sqrt(charge2 * charge2);
}
And now we can apply the same to getLetter(String compound) {...} etc.
I would throw some of that parsing into its own class, maybe you can even offload more into there when you build out more functionallity.
public class Symbol {
final int charge;
final String letter;
public Symbol(String str) {
int sepIndex = str.indexOf('^');
if(sepIndex != -1) {
letter = str.substring(0, sepIndex);
charge = Integer.parseInt(str.substring(sepIndex+1).replace("+", ""));
} else {
throw new IllegalArgumentException(str + " isnt a valid Symbol, no ^ found");
}
}
}
public class Formula {
String compound1;
String compound2;
static private Map<String, String> map = new HashMap<String, String>();
// make this a static block so its only called once.
static {
// 1+
map.put("Hydrogen", "H^1+");
map.put("Lithium", "Li^1+");
map.put("Sodium", "Na^1+");
map.put("Potassium", "K^1+");
map.put("Rubidium", "Rb^1+");
// 2+
map.put("Magnesium", "Mg^2+");
map.put("Calcium", "Ca^2+");
map.put("Strontium", "Sr^2+");
// 3+
map.put("Aluminium", "Al^3+");
// 3-
map.put("Nitrogem", "N^-3");
map.put("Phosphorus", "P^-3");
// 2-
map.put("Oxygen", "O^-2");
map.put("Sulfur", "S^-2");
map.put("Selenium", "Se^-2");
// 1-
map.put("Fluorine", "F^-1");
map.put("Chlorine", "Cl^-1");
map.put("Bromine", "Br^-1");
map.put("Iodine", "I^-1");
}
String createFormula() {
// Example1: Input = Calcium Iodine:
// 2x + -1y = 0
// x = 1 and y = 2
// Output = CaI2
//
// Example2: Input = Sulfur Iodine
// Output = Molecule: Sulfur Iodine = SI2
Symbol symbol1 = new Symbol(map.get(compound1));
Symbol symbol2 = new Symbol(map.get(compound2));
int possitive1 = Math.abs(symbol1.charge); // sqrt(a*a) == abs(a)
int possitive2 = Math.abs(symbol1.charge);
if ((possitive1 == 1) & (possitive2 == 1)) {
return symbol1.letter + symbol1.letter;
} else if (possitive1 == 1) {
return symbol1.letter + possitive2 + symbol2.letter;
} else if (possitive2 == 1) {
return symbol1.letter + symbol2.letter + possitive1;
}
// dead code, if positive1 is 0 then setting it to -0 does nothing
/*if (possitive1 == 0) {
possitive1 = -(symbol1.charge);
}
if (possitive2 == 0) {
possitive2 = -(symbol2.charge);
}*/
return symbol1.letter + possitive2 + symbol2.letter + possitive1;
}
}
First method:
getCharge(String symbol){
return Integer.parseInt(symbol.replace("+", "").substring(symbol.length() - 2));
}
Second Method:
getLetter(String symbol){
if (symbol.length() == 5) {
return symbol.substring(0, 2);
} else if (symbol.length() == 4) {
return symbol.substring(0, 1);
}
}
I believe this is equivalent to your posted code -
private static String checkCompound(String symbol) {
if (symbol.length() == 5) {
return symbol.substring(0, 2);
} else if (symbol.length() == 4) {
return symbol.substring(0, 1);
}
return "";
}
Then
String letter1 = checkCompound(symbol1);
String letter2 = checkCompound(symbol2);
if (charge1 > 0) {
if (charge2 > 0) {
return letter1 + letter2;
}
return letter1 + charge2 + letter2;
} else if (charge2 > 0) {
return letter1 + letter2 + charge1;
}
return letter1 + charge2 + letter2 + charge1;
Finally, this
if (possitive1 == 0) {
possitive1 = -(charge1);
}
was removed because it's -0 which is 0.
Well, first let's rearrange your code so that all of the ...1 variables are together. Judging by your naming convention, you use letter1 to calculate symbol1, symbol1 to calculate charge1, etc... I'm just going to focus on createFormula() since that's the part you want to reduce in size.
String createFormula() {
initiateIons();
//Calculate symbol1, charge1, letter1, possitive1
String symbol1 = map.get(compound1);
int charge1 = Integer.parseInt(symbol1.replace("+", "").substring(
symbol1.length() - 2));
String letter1 = null;
if (symbol1.length() == 5) {
letter1 = symbol1.substring(0, 2);
} else if (symbol1.length() == 4) {
letter1 = symbol1.substring(0, 1);
}
int possitive1 = (int) Math.sqrt(charge1 * charge1);
//calculate symbol2, charge2, letter2, possitive2
String symbol2 = map.get(compound2);
int charge2 = Integer.parseInt(symbol2.replace("+", "").substring(
symbol2.length() - 2));
String letter2 = null;
if (symbol2.length() == 5) {
letter2 = symbol2.substring(0, 2);
} else if (symbol2.length() == 4) {
letter2 = symbol2.substring(0, 1);
}
int possitive2 = (int) Math.sqrt(charge2 * charge2);
//Returns
if ((possitive1 == 1) & (possitive2 == 1)) {
return letter1 + letter2;
} else if (possitive1 == 1) {
return letter1 + possitive2 + letter2;
} else if (possitive2 == 1) {
return letter1 + letter2 + possitive1;
}
if (possitive1 == 0) {
possitive1 = -(charge1);
}
if (possitive2 == 0) {
possitive2 = -(charge2);
}
return letter1 + possitive2 + letter2 + possitive1;
}
I agree, the calculation step seems redundant. It would be amazing to have a function that calculates those for and returns a tuple of them, but (as far as I know) Java doesn't yet have tuples. We can do a string array though, and parse the ints back out of the strings. Here's a less redundant revision of your code.
String[] calculatePieces(String compound){
String symbol = map.get(compound);
int charge = Integer.parseInt(symbol.replace("+", "").substring(
symbol.length() - 2));
String letter = null;
if (symbol.length() == 5) {
letter = symbol1.substring(0, 2);
} else if (symbol1.length() == 4) {
letter = symbol1.substring(0, 1);
}
int possitive = (int) Math.sqrt(charge * charge);
pieces = new String[4];
pieces[0] = symbol;
pieces[1] = charge + "";
pieces[2] = letter;
pieces[3] = possitive + "";
return pieces;
}
String createFormula() {
initiateIons();
String[] pieces1 = calculatePieces(compound1);
int charge1 = Integer.parseInt(pieces1[1]);
int possitive1 = Integer.parseInt(pieces1[3]);
String[] pieces2 = calculatePieces(compound2);
int charge2 = Integer.parseInt(pieces2[1]);
int possitive2 = Integer.parseInt(pieces2[3]);
//Returns
if ((possitive1 == 1) & (possitive2 == 1)) {
return pieces1[2] + pieces2[2];
} else if (possitive1 == 1) {
return pieces1[2] + possitive2 + pieces2[2];
} else if (possitive2 == 1) {
return pieces1[2] + pieces2[2] + possitive1;
}
if (possitive1 == 0) {
possitive1 = -(charge1);
}
if (possitive2 == 0) {
possitive2 = -(charge2);
}
return pieces1[2] + possitive2 + pieces2[2] + possitive1;
}
It's a bit better, but Java's restriction on returning a single object limits how clean this can get. The way to make it even cleaner is to make a wrapper object that basically acts as a tuple of (string, int, string, int), but if you need this to be fast that's not the way to go.

Android - Simplifying Radicals

I am trying to make a calculator that performs the quadratic formula.
Currently if my result would be a decimal it returns NaN. (EDIT: Resolved)
Preferably I would like the result to be in an simplified radical form (i.e. √(99) = 3√(11) ).
How would I go about achieving this?
This is what I have so far.
// Do the math
private double mathCalcPlus(double varA,double varB,double varC) {
return ((-varB + Math.sqrt(varB * varB - 4 * varA * varC)) / 2 * varA);
}
private double mathCalcMinus(double varA,double varB,double varC) {
return ((-varB - Math.sqrt(varB * varB - 4 * varA * varC)) / 2 * varA);
}
Any help will be greatly appreciated.
This works great! However, I decided to add the top bar of the radical sign just for fun :D
import java.util.Scanner;
public class Radical {
public static void main(String[] args) {
System.out.print("Enter the unsimplified radical: ");
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
recurse(input);
}
public static void recurse(int x) {
System.out.println(" ______");
System.out.println("Attempting to simplify -/" + x);
int a = 0;
int b = 0;
int count = 0;
for (int i = 1; i < x; i++) {
if ((i * (x/i)) == x) {
//System.out.println(i + "<i rest>" + (x/i));
a = i;
b = x/i;
if (Math.sqrt(a)%1==0) {
if (a != 1) {
System.out.println(" ______");
System.out.println(" " + (int)Math.sqrt(a) + "-/" + b);
count = 1;
}
}
}
}
if (count>0) {
recurse(b);
} else if (count==0) {
System.out.println(" ______");
System.out.println("Cannot simplify -/" + x);
}
}
}
Here's something that might help as far as simplifying radicals go. Give it the unsimplified radical (let's say 850) and it should return the correct answer (5-/34). It also tries to recursively simplify what's left in the radical in case it needs to be broken down again.
This was written quickly so I'm sure there are edge cases I missed that will throw off the calculations but I hope it helps at least a little. Best of luck!
import java.util.Scanner;
public class Radical {
public static void main(String[] args) {
System.out.print("Enter the unsimplified radical: ");
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
recurse(input);
}
public static void recurse(int x) {
System.out.println("Attempting to simplify -/" + x);
int a = 0;
int b = 0;
int count = 0;
for (int i = 1; i < x; i++) {
if ((i * (x/i)) == x) {
//System.out.println(i + "<i rest>" + (x/i));
a = i;
b = x/i;
if (Math.sqrt(a)%1==0) {
if (a != 1) {
System.out.println((int)Math.sqrt(a) + "-/" + b);
count = 1;
}
}
}
}
if (count>0) {
recurse(b);
} else if (count==0) {
System.out.println("Cannot simplify -/" + x);
}
}
}

Categories