64 lines
2.8 KiB
Java
64 lines
2.8 KiB
Java
package de.janchristiangruenhage.math.multiplication;
|
|
|
|
import java.util.LinkedList;
|
|
|
|
/**
|
|
* The class <tt>LongMultiplication</tt> represents a Multiplication of two factors,
|
|
* one very very large one (basically limitless)
|
|
* and a relatively large one (more than about 25 digits make the calculation pretty confusing)
|
|
*/
|
|
public class LongMultiplication {
|
|
private String factorOne;
|
|
private String factorTwo;
|
|
private int splitInLine;
|
|
private int splitLines;
|
|
|
|
/**
|
|
* @param factorOne First Factor
|
|
* @param factorTwo Second Factor
|
|
* @param splitInLine How many digits of the first Factor will be used per multiplication
|
|
* @param splitLines How many lines of the multiplication will be added in one addition,
|
|
* If != 0 and smaller than the number of digits in the second factor,
|
|
* there will be multiple Additions per Multiplication.
|
|
*/
|
|
public LongMultiplication(String factorOne, String factorTwo, int splitInLine, int splitLines) {
|
|
this.factorOne = factorOne;
|
|
this.factorTwo = factorTwo;
|
|
this.splitInLine = splitInLine;
|
|
this.splitLines = splitLines;
|
|
}
|
|
|
|
/**
|
|
* Creates and easily readable Multiplication and returns it.
|
|
*
|
|
* @return String representation of the Calculation
|
|
*/
|
|
public String printCalculation() {
|
|
LinkedList<Multiplication> multiplications = new LinkedList<>();
|
|
//Constructing new List for Multiplications
|
|
while (factorOne.length() > splitInLine && splitInLine != 0) {
|
|
String splitFactorString = factorOne.substring(factorOne.length() - splitInLine);
|
|
factorOne = factorOne.substring(0, factorOne.length() - splitInLine);
|
|
//Cutting String for Multiplication Parts
|
|
multiplications.add(new Multiplication(splitFactorString, factorTwo, splitLines, false));
|
|
//Constructing new Multiplication and adding it to the List
|
|
}
|
|
multiplications.add(new Multiplication(factorOne, factorTwo, splitLines, true));
|
|
//Constructing last new Multiplication and adding i to the List
|
|
String retVal = "";
|
|
//Initialising the retVal String, which will be returned
|
|
for (int i = 0; i < multiplications.size(); i++) {
|
|
retVal = multiplications.get(i).printCalculation() + retVal;
|
|
//"Printing" the Multiplication, adding it to the retVal String
|
|
if (i < multiplications.size() - 1) {
|
|
//This is needed to avoid a index out of bounds exception since the next line always uses the following multiplication too
|
|
multiplications.get(i + 1).setCarry(multiplications.get(i).getResultCarry());
|
|
//Calculating the Carry for the following Multiplication
|
|
}
|
|
}
|
|
return retVal;
|
|
}
|
|
|
|
|
|
}
|