How to access specific class? - java

Hi for one of my assignments I had to make an ackermann simulator in Java and I was having trouble. The assignment was to create three variations of the ackermann project, one regular, one recursive and one through a table lookup. well, I've done all that but the part that I'm struggling with is the creating a menu for it part. I'm not sure how to access each class when I select an option from the menu. do I need a main class for every single class or one for all of them? Here is my code and I guess my biggest question is how do I get user input when I select a version of the ackermann from the menu, thank you very much.
Here is my menu:
import java.util.Scanner;
public class AckMenu
{
public static void main(String [] args) throws InterruptedException
{
Scanner scan = new Scanner(System.in);
int choiceNumber = 0;
introduction();
while (choiceNumber != 4)
{
printMenuChoices();
choiceNumber = readChoiceNumber();
switch (choiceNumber)
{
case 1:
//
AckermannValue.Ack(3,3);
break;
case 2:
AckermannTrace.Ack(1,3);
break;
case 3:
AckermannTableLookup.getValue();
break;
default:
System.out.println("The game is over.");
choiceNumber = 4;
break;
}//switch
}//while
}
private static void introduction()
{
System.out.println("\n\n" +
" This program allows you to call the Ackermann function.");
System.out.println("\n\n" + "Please choose one of the versions of the Ackermann function.");
}
private static void printMenuChoices()
{
System.out.println(""+
"1) Ackermann Value.\n"+
"2) Ackermann Trace.\n"+
"3) Ackermann Table Lookup.\n"+
"4) Quit.");
}
private static int readChoiceNumber()
{
Scanner scan = new Scanner(System.in);
int choiceNumber;
String indent = " ";
System.out.println("please enter the number of the method you want to call");
choiceNumber = scan.nextInt();
while(choiceNumber < 1 || choiceNumber > 4)
{
System.out.println(indent + "the number must be 1 through 4");
System.out.println(indent + " please enter a proper choice. ");
choiceNumber = scan.nextInt();
}
return choiceNumber;
}
}
and my 3 methods, first the regular version with no recursion.
import java.util.Scanner;
public class AckermannValue {
//public static void AckMethod() throws InterruptedException {
//static int count = 0;
public static int Ack(int m, int n) {
if (m < 0 || n < 0) {
throw new IllegalArgumentException("Non-negative args only!");
}
if (m == 0)
{
//count++;
//System.out.println("count: " + count + " M: " + m + " N: " + n);
return n + 1;
}
else if (n == 0)
{
//count++;
// System.out.println("count: " + count + " M: " + m + " N: " + n);
return Ack(m-1, 1);
}
else {
//count++;
//System.out.println("count: " + count + " M: " + m + " N: " + n);
return Ack(m-1, Ack(m,n-1));
}
}
//public static void main (String args [] ) {
//System.out.println(Ack(3,7));
//}
}
//}
Recursive method
import java.util.Scanner;
public class AckermannTrace {
static int count = 0;
public static int Ack(int m, int n) {
if (m < 0 || n < 0) {
throw new IllegalArgumentException("Non-negative args only!");
}
if (m == 0)
{
count++;
System.out.println("count: " + count + " M: " + m + " N: " + n);
return n + 1;
}
else if (n == 0)
{
count++;
System.out.println("count: " + count + " M: " + m + " N: " + n);
return Ack(m-1, 1);
}
else {
count++;
System.out.println("count: " + count + " M: " + m + " N: " + n);
return Ack(m-1, Ack(m,n-1));
}
}
//public static void main (String args [] ) {
//System.out.println(Ack(3,7));
//}
}
The table lookup version of the ackermann
import java.util.Hashtable;
public class AckermannTableLookup {
/**
* The table containing the values of <i>Ackermann</i>'s function.
*/
private Hashtable<Integer, Hashtable<Integer, Integer>> table;
/**
* Constructs a new table, computing all values of <i>Ackermann</i>'s
* function <i>A(i, j)</i> that are <i>n</i> or less.
*
* #param n
* the maximum value of the new table
*/
public void AckermannTable(int n) {
// construct new table
table = new Hashtable<Integer, Hashtable<Integer, Integer>>();
// set first value
int i = 1;
int j = 2;
setValue(1, 1, 2);
while (true) {
int newValue = -1;
// compute next entry
if (i == 1) {
newValue = getValue(i, j - 1) * 2;
} else {
newValue = getValue(i - 1, getValue(i, j - 1));
}
if (newValue > n || newValue == -1) {
if (j == 1) {
// no single entry in this row - return
return;
} else {
// go to the next row
i++;
j = 1;
}
} else {
// save the computed value
setValue(i, j, newValue);
j++;
}
}
}
/**
* Returns the value of <i>Ackermann</i>'s function <i>A(i, j)</i>, if it
* is <i>n</i> or less, and <code>-1</code> otherwise.
*
* #param i
* the first parameter for <i>Ackermann</i>'s function
* #param j
* the second parameter for <i>Ackermann</i>'s function
* #return
* <i>A(i, j)</i>
*/
public int getValue(int i, int j) {
if (j == 0) {
return 2;
} else {
if (table.containsKey(i)) {
Hashtable<Integer, Integer> rowI = table.get(i);
if (rowI.containsKey(j)) {
return rowI.get(j);
} else {
return -1;
}
} else {
return -1;
}
}
}
/**
* Returns the inverse value of <i>Ackermann</i>'s function <i>A(m, n)</i>.
*
* #param m
* the first parameter for the inverse <i>Ackermann</i>'s function
* #param n
* the second parameter for the inverse <i>Ackermann</i>'s function
* #return
* the inverse of <i>A(m, n)</i>
*/
public int getInverse(int m, int n) {
if (n >= 4) {
int j = 0;
while (2 * getValue(m, j) <= n && getValue(m, j) != -1) {
j++;
}
return j - 1;
} else if (m >= n) {
int i = 1;
while (getValue(i, (int)Math.floor(m / n)) != -1) {
i++;
}
return i;
}
return -1;
}
/**
* Adds the passed value of <i>Ackermann</i>'s function <i>A(i, j)</i> to
* this table.
*
* #param i
* the first parameter for <i>Ackermann</i>'s function
* #param j
* the second parameter for <i>Ackermann</i>'s function
* #param value
* <i>A(i, j)</i>
*/
private void setValue(int i, int j, int value) {
if (!table.containsKey(i)) {
table.put(i, new Hashtable<Integer, Integer>());
}
Hashtable<Integer, Integer> rowI = table.get(i);
rowI.put(j, value);
}
}

Make sure all your classes are in the same package.
Then either make all your methods static to call them by their class names(in your lookup table class) OR
You just need to modify your switch statement.
Don't call the Ack by its classname. First create an object of its class and then call that function. For example in case1 :
AckermannValue object1 = new AckermannValue();
object1.Ack(3,3);
Now your program will run fine.

Related

How to format multiplication table into 4 rows and columns respectively and test for even number multiplication table between 1 and 9?

This is the code I atempted with the guide of external video which didnt cover expected output in terms of formatting
public class Lab3Class {
public static void main(String[] args) {
// TODO Auto-generated method stub
int table = 1;
while(table<10) {
int i = 1;
while(i<=10)
{
System.out.println(table+ " * "+i+" = "+(table*i));
i++;
}
System.out.println(" ");
table++;
}
}
}
You are just missing a check for even numbers i.e. if (table % 2 == 0).
public class Main {
public static void main(String[] args) {
int table = 1;
while (table < 10) {
if (table % 2 == 0) {
int i = 1;
while (i <= 10) {
System.out.println(table + " * " + i + " = " + (table * i));
i++;
}
}
System.out.println();
table++;
}
}
}
Alternatively, you can start table with 2 and increment it by 2 in each iteration as follows:
public class Main {
public static void main(String[] args) {
int table = 2;
while (table < 10) {
int i = 1;
while (i <= 10) {
System.out.println(table + " * " + i + " = " + (table * i));
i++;
}
System.out.println();
table += 2;
}
}
}
If you need to print it in a tabular structure, you can write the loops as follows:
public class Main {
public static void main(String[] args) {
for (int line = 1; line <= 10; line++) {
for (int i = 2; i <= 10; i += 2) {
System.out.print(i + "*" + line + "=" + (i * line) + "\t");
}
System.out.println();
}
}
}
Output:
2*1=2 4*1=4 6*1=6 8*1=8 10*1=10
2*2=4 4*2=8 6*2=12 8*2=16 10*2=20
2*3=6 4*3=12 6*3=18 8*3=24 10*3=30
2*4=8 4*4=16 6*4=24 8*4=32 10*4=40
2*5=10 4*5=20 6*5=30 8*5=40 10*5=50
2*6=12 4*6=24 6*6=36 8*6=48 10*6=60
2*7=14 4*7=28 6*7=42 8*7=56 10*7=70
2*8=16 4*8=32 6*8=48 8*8=64 10*8=80
2*9=18 4*9=36 6*9=54 8*9=72 10*9=90
2*10=20 4*10=40 6*10=60 8*10=80 10*10=100
As you can see, it looks cleaner by using a for loop. However, I recommend you also practice it with a while loop. Once you gain more confidence, I also recommend you use String::format or System.out.printf for better formatting.
This is a very small data set but if the dataset is huge, you can improve the performance by reducing the I/O operation. For this, you can append the result to a StringBuilder and print it just once at the end.
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int line = 1; line <= 10; line++) {
for (int i = 2; i <= 10; i += 2) {
sb.append(i).append('*').append(line).append('=').append(i * line).append('\t');
}
sb.append('\n');
}
System.out.println(sb);
}
}

Negascout for Tic-Tac-Toe in java

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication7.ai;
import javaapplication7.model.Move;
import javaapplication7.model.TicTacToeGame;
/**
*
* #author Harshal
*/
public class NegaScout extends Strategy{
#Override
public Move makeMove(TicTacToeGame game) {
System.out.println("Negascout");
Move move = game.getAvaiableMoves().get(0);
int best = Integer.MIN_VALUE;
for(int i=0; i<game.getAvaiableMoves().size(); i++){
System.out.print(game.getAvaiableMoves().get(i) + ",");
}
System.out.println();
for (int i = 0; i < game.getAvaiableMoves().size(); i++) {
//int result = negaMax(game);
//TicTacToeGame tmp = game.clone();
//tmp.playMove(game.getAvaiableMoves().get(i));
int result = negaScout(game, Integer.MIN_VALUE, Integer.MAX_VALUE);
//System.out.println("for i = " + i + " : " + game.getAvaiableMoves().get(i) + " result : " + result);
System.out.printf("%d %d\n",best,result);
if (result > best) {
move = game.getAvaiableMoves().get(i);
best = result;
}
}
System.out.println();
return move;
}
private int negaScout(TicTacToeGame game, int a, int b){
if (Move.isWon(game.getCurrentPlayer().getMoves())) {
return 1;
}
if (Move.isWon(game.getNonCurrentPlayer().getMoves())) {
return -1;
}
//int score;
int score = Integer.MIN_VALUE;
for (int i = 0; i < game.getAvaiableMoves().size(); i++) {
//Move move = game.getAvaiableMoves().get(i);
//TicTacToeGame tmp = game.clone();
Move move = game.getAvaiableMoves().get(i);
TicTacToeGame tmp = game.clone();
tmp.switchPlayers();
tmp.playMove(move);
if(i==0){
score = -negaScout(tmp,-b,-a);
}else{
score = -negaScout(tmp, ((-a)-1), -a);
if(a<score && score<b)
score = -negaScout(tmp, -b, -score);
}
a = Math.max(a,score);
if(a >= b){
break;
}
}
return a;
}
}
I am trying to implement negascout for tic-tac-toe, but the alglorithm doesn't do anything.
It only chooses the first move in the set of available moves.
It returns values but i couldn't trace them.
Some help will be appreciated.

Overridden method from interface not found when calling

I'm trying to call a divide method that's overridden from an interface class. All similar methods (add, subtract, multiply) work just fine, except divide for some reason isn't found. Here's what I have below:
Arithmetic Interface class
public interface Arithmetic {
public Object add(Object obj);
public Object subtract(Object obj);
public Object multiply(Object obj);
public Object divide(Object obj);
}
Number class (Arithmetic methods are overridden below, divide being the last one)
public class Number implements Comparable,Arithmetic{
/**
* A string representing a non-negative number
*/
private String value;
/**
* An integer greater than or equals to 2.
*/
private int base;
/**
* - for negative numbers and otherwise null
*/
private char sign;
/**
* creates 0 base 2.
*/
public Number()
{
value = "0";
base = 2;
}
/**
* creates a number in a specified based using the specified parameters.
* #param num a string representing a non-negative number with digit
* written in uppercase letters.
* #param radix the base of the number
*/
public Number(String num, int radix) throws InvalidNumberException
{
String list = ".-0123456ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Boolean pars = false;
for (int i = 0; i < list.length(); i++) {
if (num.indexOf(list.charAt(i)) != -1) {
pars = true;
}
}
if (radix < 1 || radix > 35) {
throw new InvalidNumberException("Number invoked with a radix less than 1 or greater than 35.");
} else if ((num.indexOf(".") != num.lastIndexOf(".")) || (num.indexOf("-") != num.lastIndexOf("-"))) {
throw new InvalidNumberException("Number invoked with more than one dash or period in string.");
} else if (num.indexOf("-") != 0) {
throw new InvalidNumberException("Number invoked with dash not at beginning of string.");
} else if (num.indexOf(".") == num.length()) {
throw new InvalidNumberException("Number invoked with period at end of string.");
}
else if (pars == true) {
throw new InvalidNumberException("Number invoked with invalid character.");
}
Boolean test=false;
for (int i = 0; i < num.length(); i++) {
if ((num.charAt(i) != '-') || (num.charAt(i) != '.')) {
if (toValue(num.charAt(i)) >= radix) {
test=true;
throw new InvalidNumberException("Number invoked with digit greater or equal to radix.");
}
}
}
if(test==false){
value = num;
base = radix;
}
}
/**
* Converts a digit to its integer equivalent
* #param digit 0...9 or A...Z to be converted
* #return the integer equivalent of the specified digit.
*/
private int toValue(char digit)
{
return Character.getNumericValue(digit);
}
/**
* Converts this integer to its equivalent digit
* #param anInt an integer between 0-35
* #return the digit equivalent to an integer
*/
private char toDigit(int anInt)
{
if(anInt >= 0 && anInt <= 9)
return (char)(anInt + 48);
else if(anInt >= 10 && anInt <= 35)
return (char)(anInt + 55);
else
return (char)(-1);
}
/**
* converts a number to its decimal equivalent (double).
* #return the decimal equivalent of a number
*/
private double toDouble()
{
if (base == 10)
return Double.parseDouble(value);
int periodIndex = value.indexOf('.');
double base10Num = 0;
int i;
int radix = base;
String whole;
if (periodIndex >=0)
whole = value.substring(0, periodIndex);
else
whole = value;
int j=0;
int wholeLength = whole.length();
for (i=wholeLength-1; i>=0; i--)
base10Num = base10Num + toValue(whole.charAt(i))*(int)Math.pow(radix,wholeLength-i-1);
if (periodIndex >= 0)
{
String fract = value.substring(periodIndex+1,value.length());
int fractLength = fract.length();
for (i=0; i<fractLength; i++)
{
base10Num = base10Num + toValue(fract.charAt(i))*Math.pow(radix,-i-1);
}
}
if (sign == '-')
base10Num *= -1;
return base10Num;
}
/**
* converts a decimal number (double) to its equivalent representation
* in a given base.
* #param dec the decimal (base 10) number
* #radix the base to convert the number to.
* #return the equivalent number in the specified base
*/
private Number doubleToNumber(double dec, int radix)
{
if (radix == 10)
return new Number(Double.toString(dec),radix);
String numSign="";
if (dec < 0)
{
numSign = "-";
dec = -dec;
}
int whole = (int)dec;
double fract = dec - whole;
String numStr = "";
while (whole != 0)
{
numStr = toDigit(whole%radix) + numStr;
whole = whole / radix;
}
if (fract != 0)
{
numStr += ".";
int tolerance = 20;
int precision = 0;
while (precision < tolerance && fract != 0)
{
fract = fract * radix;
numStr += toDigit((int)(fract));
precision++;
fract = fract - (int)fract;
}
}
return new Number(numSign+numStr,radix);
}
/**
* Gives a string representation of this number in the
* format number[base].
* #return a string representation of this number
*/
#Override
public String toString()
{
return String.format("%s%s[%d]", this.sign, this.value, this.base);
}
#Override
public boolean equals(Object obj)
{
if (!(obj instanceof Number))
return false;
return (this.toDouble()==((Number)obj).toDouble());
}
#Override
public int compareTo(Object obj) throws IllegalArgumentException
{
if (!(obj instanceof Number))throw new IllegalArgumentException();
else if(this.toDouble()<((Number)obj).toDouble()) return -1;
else if(this.toDouble()>((Number)obj).toDouble()) return 1;
else return 0;
}
/**
* This method adds two numbers from two different objects
* #param obj the number of the object inputted from user
* #return a new added number object
*/
#Override
public Object add(Object obj) throws IllegalArgumentException {
if (!(obj instanceof Number)) {
throw new IllegalArgumentException();
} else if (this.base != ((Number) obj).base) {
throw new IllegalArgumentException();
} else {
return doubleToNumber((this.toDouble() + ((Number) obj).toDouble()), ((Number) obj).base);
}
}
/**
* This method subtracts two numbers from two different objects
* #param obj the number of the object inputted from user
* #return a new subtracted number object
*/
#Override
public Object subtract(Object obj) throws IllegalArgumentException {
if (!(obj instanceof Number)) {
throw new IllegalArgumentException();
} else if (this.base != ((Number) obj).base) {
throw new IllegalArgumentException();
} else {
return doubleToNumber((this.toDouble() - ((Number)obj).toDouble()), ((Number) obj).base);
}
}
/**
* This method multiplies two numbers from two different objects
* #param obj the number of the object inputted from user
* #return a new multiplied number object
*/
#Override
public Object multiply(Object obj) throws IllegalArgumentException{
if (!(obj instanceof Number)) {
throw new IllegalArgumentException();
} else if (this.base != ((Number) obj).base) {
throw new IllegalArgumentException();
} else {
return doubleToNumber(this.toDouble() * ((Number)obj).toDouble(), ((Number) obj).base);
}
}
/**
* This method divides two numbers from two different objects
* #param obj the number of the object inputted from user
* #return a new divided number object
*/
#Override
public Object divide(Object obj) throws IllegalArgumentException {
if (!(obj instanceof Number)) {
throw new IllegalArgumentException();
} else if (this.base != ((Number) obj).base) {
throw new IllegalArgumentException();
} else if (((Number) obj).toDouble() == 0) {
throw new IllegalArgumentException();
} else {
return doubleToNumber((this.toDouble() / ((Number) obj).toDouble()), ((Number) obj).base);
}
}
}
And finally my demo class, NumberDemo
public class NumberDemo
{
public static void main(String[] args)
{
Number a = new Number("12.25", 8);
Number b = new Number("13.75", 8);
System.out.println(a.toString() + " + " + b.toString() + " = " +
a.add(b));
a = new Number("ABC.75", 16);
b = new Number("18.5F", 16);
Number c = new Number("2.FB", 16);
System.out.println("(" + a.toString() + " - " + b.toString() + ") / " +
c.toString() + " = " + (a.subtract(b)).divide(c));
a = new Number("3.45", 9);
b = new Number("32.25", 9);
c = new Number("3.05", 9);
System.out.println(a.toString() + "(" + b.toString() + " + " +
c.toString() + " = " + a.multiply(b.add(c)));
a = new Number("10111.11", 2);
b = new Number("1100110.01", 2);
c = new Number("-101", 2);
System.out.println("(" + a.toString() + " - " + b.toString() + ") / " +
c.toString() + " = " + (a.subtract(b)).divide(c));
a = new Number("-5", 8);
b = new Number("5", 8);
System.out.println(a.toString() + " x " + b.toString() + " = " +
a.multiply(b));
a = new Number("-0.5", 8);
b = a;
System.out.println(a.toString() + " x " + b.toString() + " = " +
a.multiply(b));
}
}
When I call all the arithmetic methods, they appear to be called just fine, however calling divide brings me the error tooltip:
cannot find symbol
symbol: method divide(Number)
location: class Object
I can't seem to find the reason for this, can anyone spot it?
This is my first time using Stockoverflow, so please let me know if anything's apart from the format norm.

Can anyone tell me how to improve the run time of this code?

I have written a program to solve Diophantine equations in the form
A5 + B5 + C5 + D5 + E5 = 0;
It should run in N3long(N) time, but it usually takes about 10 minutes for an input size of 100. Can anyone tell me whats wrong?
public class EquationSolver {
//Solves Equations of type: A^5 + B^5 + C^5 + D^5 + E^5 = F^5
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a max value: ");
int N = input.nextInt();
long START_TIME = System.nanoTime();
SLinkedList test = new SLinkedList();
SLinkedList test2 = new SLinkedList();
test = setupLeftList(N);
test2 = setupRightList(N);
System.out.println("Note: This program takes about 7 minutes to complete for input of 100");
test = mergeSort(test);
test2 = mergeSort(test2);
long END_TIME2 = System.nanoTime() - START_TIME;
System.out.println("Total Time:" + END_TIME2/1000000000.0);
checkEquality(test, test2);
long END_TIME3 = System.nanoTime() - START_TIME;
System.out.println("Total Time:" + END_TIME3/1000000000.0);
}
public static SLinkedList setupLeftList(long boundary)
{
//Creates and returns an linkedList of all possible A,B,C values and their sums
SLinkedList leftSums = new SLinkedList();
for(long c = 0; c < boundary; c++)
{
for(long b = 0; b < c; b++)
{
for(long a = 0; a < b; a++)
{
long sum = (long)(Math.pow(a+1,5)) + (long)(Math.pow(b+1, 5)) + (int)(Math.pow(c+1, 5));
Node current = new Node (sum, a+1, b+1, c+1, null);
//System.out.println(sum);
leftSums.addLast(current);
}
}
}
return leftSums;
}
public static SLinkedList setupRightList(long boundary)
{
//Creates and returns an linkedList of all possible D,E,F values and their sums
SLinkedList rightSums = new SLinkedList();
for(int f = 0; f < boundary; f++)
{
for(int e = 0; e < f; e++)
{
for(int d = 0; d < e; d++)
{
long sum = (long)(Math.pow(f+1, 5)) - ((long)(Math.pow(d+1, 5)) + (long)(Math.pow(e+1,5)));
Node current = new Node (sum, d+1, e+1, f+1, null);
//System.out.println(current.getSum());
rightSums.addLast(current);
}
}
}
return rightSums;
}
public static SLinkedList mergeSort(SLinkedList sums)
// Sorts each list by the value of the sum
{
if (sums.length() > 1 )
{
SLinkedList[] splitList = split(sums);
SLinkedList s1 = mergeSort(splitList[0]);
SLinkedList s2 = mergeSort(splitList[1]);
sums = merge(s1, s2);
}
return sums;
}
public static SLinkedList[] split(SLinkedList sums)
{
// Splits a linked list into two (somewhat) equal halves
long midpoint = sums.length()/2;
Node midPoint = sums.elementAt(midpoint);
SLinkedList s1 = new SLinkedList(sums.head, midPoint, midpoint);
SLinkedList s2 = new SLinkedList(midPoint, sums.tail, midpoint);
SLinkedList[] both = new SLinkedList[]{s1, s2};
return both;
}
public static SLinkedList merge(SLinkedList s1, SLinkedList s2)
{
// Merges two sorted lists of elements
SLinkedList sMerged = new SLinkedList();
while(!s1.isEmpty() && !s2.isEmpty())
{
if (s1.getFirst().getSum() < s2.getFirst().getSum())
{
sMerged.addLast(s1.removeFirst());
}
else
{
sMerged.addLast(s2.removeFirst());
}
}
while(!s1.isEmpty())
{
sMerged.addLast(s1.removeFirst());
}
while(!s2.isEmpty())
{
sMerged.addLast(s2.removeFirst());
}
return sMerged;
}
public static void checkEquality(SLinkedList left, SLinkedList right)
{
// Checks two linked lists for nodes that contain the same Sum value
boolean ans = false;
while (left.isEmpty() == false && right.isEmpty() == false)
{
long currentLeft = left.getFirst().getSum();
long currentRight = right.getFirst().getSum();
if (currentLeft > currentRight)
{
right.removeFirst();
}
else if(currentLeft < currentRight)
{
left.removeFirst();
}
else
{
if (left.getFirst().getC() <= right.getFirst().getA())
{
System.out.println("Answer Found: " + "A: " + left.getFirst().getA() + " B: " + left.getFirst().getB() + " C: "
+ left.getFirst().getC() + " D: " + right.getFirst().getA() + " E: " + right.getFirst().getB() + " F: " + right.getFirst().getC());
ans = true;
}
Node temp = left.getFirst().getNext();
while (temp.getSum() == currentRight)
{
if (temp.getC() <= right.getFirst().getA())
{
System.out.println("Answer Found: " + "A: " + left.getFirst().getA() + " B: " + left.getFirst().getB() + " C: "
+ left.getFirst().getC() + " D: " + right.getFirst().getA() + " E: " + right.getFirst().getB() + " F: " + right.getFirst().getC());
ans = true;
}
temp = temp.getNext();
}
right.removeFirst();
left.removeFirst();
}
}
if (ans == false)
{
System.out.println("No answer found.");
}
}
}
The definitive answer is: use a profiler and see what causes a bottleneck...
But I see you have Math.pow() calls, all with longs, and their 5th power.
You could do it quicker, while even detecting the overflow:
public static long pow5(long base) {
if(base <=6208 && base >=-6208) {
return base*base*base*base*base;
} else {
throw new IllegalArgumentException("Overflow!");
}
}
(Magic number disclaimer: 62085 is ~263, is a number is bigger than that, the 5th power won't fit into 64 bits...)
Math.pow uses doubles, which means a lot of conversion in itself...
Also, #Floris pointed out that it is not even worth computing this over and over again - it could be put into a nice array, and just index that
public static long[] pow5 = getPow5(100);
public static long[] getPow5(long numElements) {
long[] toReturn = new long[numElements];
for(long i=0;long<numElements;long++) {
toReturn[i] = i*i*i*i*i;
}
return toReturn;
}
And where needed, instead of Math.pow(x, 5) just use pow5[x]

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