Is there a way to implement a long division algorithm in java, not on numbers bu
ID: 3665252 • Letter: I
Question
Is there a way to implement a long division algorithm in java, not on numbers but on array representations of numbers?
for example, if I have 320 as the dividend and 4 as the divisor, they would be represented as follows:
short[] dividend = {0,2,3}
short[] divisor = {4}
So the quotient is 80 remainder 0
then I would want the quotient to be represented as either an array with {0,8} and a short holding the remainder 0
(unless there is a better way)
******THE OPERATIONS CANNOT BE DONE ON NUMBERS BECAUSE THERE WILL BE RISK OF OVERFLOW THAT IS WHY WE ARE USING ARRAYS*******
assume that we already have algorithms that can perform addition, subtraction, and multiplication on arrays of type short.
Explanation / Answer
Rather than number representing in array format... converting numbers into binary array format... type String array
Here is the pseudocode..
int first = 320;
int second = 4;
int temp = second;
int quot = 0;
//convert number to binary format
//using INteger.toBinaryString(...)
String divisor = Integer.toBinaryString(first);
String dividend = Integer.toBinaryString(second);
//now store lengthh
int divisorLength = divisor.length();
int dividendLength = dividend.length();
int requiredPower = divisorLength - dividendLength;
second = (int) (second * Math.pow(2, requiredPower));
//now while loop to access all binary inputs
while(first > temp){
//checking whether divisor is greater than dividend
if(first >= second){
//subtracting result
first = first - second;
quot = quot*2+1; //multiply by 2 since it is binary
second = second/2;
}
else{
quot = quot*2; //multiply by 2 since it is binary
second = second/2;
}
//now in the quotient quot we have the resultant answer
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.