Java long division without / operator having problem with quotient, remainder - java

I wrote a division method that does long division without / operator but when I run a unit-test it gives me correct quotient but the wrong remainder.
This is my division method:
public MyBigInteger dividedBy(MyBigInteger divisor) throws Exception {
int x = 0;
int temp = 0;
int count = 0;
int y = 10;
int total = 0;
int total2 = 0;
reverse(coefficients);
reverse(divisor.coefficients);
int current = 1;
int quotient = 0;
for (Integer i : coefficients) {
total = 10 * total + i;
}
for (Integer j : divisor.coefficients) {
total2 = 10 * total2 + j;
}
if (total2 > total) {
throw new Exception("The answer is 0");
}
if (total2 == total) {
throw new Exception("The answer is 1");
}
while (total2 <= total) {
total2 <<= 1;
current <<= 1;
}
total2 >>= 1;
current >>= 1;
while (current != 0) {
if (total >= total2) {
total -= total2;
quotient |= current;
}
current >>= 1;
total2 >>= 1;
}
MyBigInteger answer = new MyBigInteger(quotient, this.base);
return answer;
}
And this is the test-code:
quo = big1.divide(big2).toString(base);
quo = "(" + quo + ")_" + base;
System.out.print("divide: big1/big2 = "); // BigInteger
System.out.println(quo);
long s_time = System.currentTimeMillis();
System.out.print("divide: n1/n2 = "); // MyBigInteger
try {
quo_mybig = n1.dividedBy(n2).toString();
System.out.println(quo_mybig);
System.out.println("Time Required (Divide): " + (System.currentTimeMillis() - s_time) + " ms");
System.out.println(remarks);
if (quo.contentEquals(quo_mybig))
System.out.println("Test passed.");
else
System.out.println("Test failed.");
}
And this is what I got
big1: (3956)_10 (BigInteger)
big2: (27)_10 (BigInteger)
n1: (3956)_10 (MyBigInteger)
n2: (27)_10 (MyBigInteger)
divide: big1/big2 = (146)_10
divide: n1/n2 = (146)_10
Time Required (Divide): 0 ms
Remarks: An efficent implementation finds a solution within 1 ms.
Test passed.
big1 mod big2 = (14)_10
n1 mod n2 = (1499)_10
Test failed.
When I put MyBigInteger answer = new MyBigInteger(146,this.base); instead of MyBigInteger answer = new MyBigInteger(quotient,this.base); I get the mod test passed even though the quotient is 146 (checked with system.out.println)
I have no idea what is wrong here. Please help...

Related

Is this adding bases function correct?

So I have an assignment I have that I did and works most of the time however for some reason, for some values it won't work. Here is the assignment:
https://i.stack.imgur.com/h5FOK.png
Here is my code (sorry for the wall of text, please help me):
public static int findDigitSum(int num, int base, int start) {
int answer = 0;
int stat = start;
int inc = 0;
boolean act = false;
int ans = 0;
int mult = 1;
int carry = 0;
int sum = 0;
int digit = 0;
int digit2 = 0;
int if1 = 0;
int value = 0;
int x2 = 0;
for (int i = 0; i < num; i++) {
inc = i;
stat = start;
mult = 1;
carry = 0;
while (stat > 0 || inc > 0 || carry > 0) { // should loop how many times it needs to?
digit = stat % 10; // takes unit digit of start
sum = digit + inc + carry; // creates sum of unit digit, inc, and carry
System.out.println("digit, sum: " + digit + " " + sum);
System.out.println("stat, inc, carry: " + stat + " " + inc + " " + carry);
value = sum % base; // takes the new digit value (modulo of base)
carry = sum / base; // finds the carry after (for next loop)
if (inc > 9) {
carry = carry - 1;
}
answer = answer + (mult * value); // adds answer to answer (mult 10)
mult = mult * 10;
stat = stat / 10; // finds 10's digit number for next loop
inc = inc / 10; // finds 10's digit for increment number for next loop
}
System.out.println("ans: " + ans);
System.out.println("answer: " + answer);
x2 = answer;
while (x2 > 0) {
ans = ans + x2 % 10;
x2 = x2 / 10;
}
stat = stat + inc;
answer = 0;
}
return ans;
}
Basically, the question is asking on how to add bases together. I coded this but for some reason some values don't work and I honestly have no idea why. Everything seems like it should work.
For example, when num is 25, base is 5, start is 324, for the variable 'ans' it returns 194 instead of 189 (the correct one). Someone please help me with this, I really need help.
The code doesn't work as expected, although it should technically work. I don't know what's wrong.

How calculate number higher than limit, and use BigInteger

Below code calculates the sum of digits of 2^15 and working. If I change for loop condition to 15, d2 becomes 2^16. --> I want 2^15.
Then I change it to 999, the sum of digits didn't match. (Sum: 1189)
Is there another way to do it?
public void go()
{
int sum = 0;
BigInteger d2 = BigInteger.ONE.add(BigInteger.ONE);
BigInteger two = d2;
for(int i = 0; i < 14; i++)
{
System.out.println(d2);
d2 = d2.multiply(two);
}
System.out.println("\n" + d2);
double val = d2.doubleValue();
double temp = val;
while(val > 0)
{
temp = val % 10;
val /= 10;
sum += temp;
System.out.println(temp);
}
System.out.println("Sum: " + sum);
}
You switch to double to calculate the sum of digits, when it looks like BigInteger.divideAndRemainder is what you need.
You would get something like:
temp = d2;
while (temp.compareTo(BigInteger.ZERO) > 0) {
BigInteger[] divideAndRemainder = temp.divideAndRemainder(BigInteger.valueOf(10));
temp = divideAndRemainder[0];
sum = sum.add(divideAndRemainder[1]);
}

Large Number Power Method

I can't figure out why, but when the power function is used, it adds a (what seems to be random) integer into the middle of the answer. I can't figure out why, can any of you see anything unusual? Thanks
//multiplication method
public IntValue Multiply(IntValue multiplier) {
StringBuilder product = new StringBuilder();
int pos = 0;
for (int i = multiplier.getValue().length() - 1; i >= 0; i--) {
int currentPosition = pos++;
int carry = 0;
int multiplierDigit = Character.getNumericValue(multiplier.getValue().charAt(i));
for (int j = value.length() - 1; j >= 0; j--) {
int multiplicandDigit = Character.getNumericValue(value.charAt(j));
int tempProduct = currentPosition < product.length()
? Character.getNumericValue(product.charAt(currentPosition)) : 0;
int currentProduct = (multiplicandDigit * multiplierDigit) + carry + tempProduct;
if (currentProduct > 9) {
carry = currentProduct / 10;
currentProduct = currentProduct % 10;
}
if (currentPosition < product.length()) {
product.setCharAt(currentPosition, Character.forDigit(currentProduct, 10));
} else {
product.append(currentProduct);
}
++currentPosition;
}
if (carry > 0) {
if (currentPosition < product.length()) {
product.setCharAt(currentPosition, Character.forDigit(carry, 10));
} else {
product.append(carry);
}
}
}
return new IntValue(product.reverse().toString());
}
//number1 and number2 are IntValues.
//power method
public IntValue Power(long n) {
IntValue result = new IntValue("1");
for(int i = 0; i < n; i++) {
result = result.Multiply(this);
}
return result;
}
System.out.println("Result = "+number1.Power(Long.parseLong(number2.toString())));
Try the following code:
BigInteger number1 = new BigInteger("5");
System.out.println("Result = " + number1.pow(5).toString());
It's how we do it in java.
There is a library for working with powers in Java, namely Math.pow (for small numbers) and BigInteger pow (for arbitrary large numbers). Note that BigInteger power cannot compute fractional powers.
There are iterative DIY algorithms for fractional powers as well, for example
BigInteger sqrt(BigInteger n) {
BigInteger a = BigInteger.ONE;
BigInteger b = new BigInteger(n.shiftRight(5).add(new BigInteger("8")).toString());
while(b.compareTo(a) >= 0) {
BigInteger mid = new BigInteger(a.add(b).shiftRight(1).toString());
if(mid.multiply(mid).compareTo(n) > 0) b = mid.subtract(BigInteger.ONE);
else a = mid.add(BigInteger.ONE);
}
return a.subtract(BigInteger.ONE);
}

Adding and subtracting string numbers in Java

I'm supposed to create a program where a user enters two numbers that could be negative or positive and could contain decimal places or not. Theoretically, when you add say "256.78 + 78.6783" it is supposed to carry the one like a normal addition problem and finish the operation.
I have figured out how to add numbers of any length only when they are positive which took me FOREVER, but when I add negative numbers or even subtract the number I don't get the correct result. This is supposed to work with any set of two numbers that a user enters.
Here is my code so far, any suggestions?
P.S. I'm NOT allowed to convert these numbers to int's or double's before the operation so Parsing them is out of the question.
public class Number {
static Scanner kbd = new Scanner (System.in);
private String sign;
private String whole;
private String decimal;
private String fraction;
private static double firstNumber;
private static double secondNumber;
public static void main(String[] args) {
System.out.println("Please enter the first number: ");
firstNumber = kbd.nextDouble();
System.out.println("Next, enter the second number: ");
secondNumber = kbd.nextDouble();
Number x = new Number (firstNumber);
Number y = new Number (secondNumber);
Number sum = x.add(y);
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("x + y = " + sum);
Number subtract = x.subtract(y);
System.out.println("x - y = " + subtract);
}
public Number()
{
whole = "0";
decimal = "0";
sign = "+";
}
public String toString()
{
return sign + whole + "." + decimal;
}
public Number (double n)
{
whole = "0";
decimal = "0";
sign = "+";
String numString = new Double(n).toString();
if (numString.charAt(0) == '-') {
sign ="-";
numString = numString.substring(1);
}
int position = numString.indexOf(".");
if (position == -1)
whole = numString;
else
{
whole = numString.substring(0,position);
decimal = numString.substring(position+1);
fraction = "";
}
}
public Number add (Number RHS) {
this.fixWhole (RHS);
this.fixDecimal(RHS);
return this.addNum (RHS);
}
public Number subtract (Number RHS) {
this.fixWhole(RHS);
this.fixDecimal(RHS);
return this.subtractNum (RHS);
}
private void fixWhole (Number RHS) {
int firstWholeNum = this.whole.length();
int secondWholeNum = RHS.whole.length();
int difference = firstWholeNum - secondWholeNum;
if (difference > 0) {
for (int i = 1; i <= difference; i++)
RHS.whole = "0" + RHS.whole;
}
else if (difference < 0 ) {
difference = Math.abs(difference);
for (int i = 1; i <= difference; i++)
this.whole = "0" + this.whole;
}
}
private void fixDecimal (Number RHS ) {
int firstDecimalNum = this.decimal.length();
int secondDecimalNum = RHS.decimal.length();
int difference = firstDecimalNum - secondDecimalNum;
if (difference > 0) {
for (int i = 1; i <= difference; i++)
RHS.decimal = RHS.decimal + "0";
}
else if (difference < 0 )
{
difference = Math.abs(difference);
for (int i = 1; i <= difference; i ++)
this.decimal = this.decimal + "0";
}
}
private Number addNum (Number RHS ) {
Number sum = new Number();
sum.decimal = "";
int carry = 0;
int decimalNum = this.decimal.length();
for (int i = decimalNum - 1; i >= 0; i --) {
char c1 = this.decimal.charAt(i);
char c2 = RHS.decimal.charAt(i);
int tempSum= (c1 - 48) + (c2 - 48) + carry;
carry = tempSum/ 10;
int sumDigit = tempSum % 10;
sum.decimal = (char) (sumDigit + 48) + sum.decimal;
}
sum.whole = "";
int wholeNum = this.whole.length();
for (int i = wholeNum - 1; i >= 0; i --) {
char c1 = this.whole.charAt(i);
char c2 = RHS.whole.charAt(i);
int tempSum = (c1 - 48) + (c2 - 48 ) + carry;
carry = tempSum / 10;
int sumDigit = tempSum % 10;
sum.whole = (char) (sumDigit + 48) + sum.whole;
}
if (carry != 0)
sum.whole = "1" + sum.whole;
return sum;
}
private Number subtractNum (Number RHS ) {
Number sum = new Number();
sum.decimal = "";
int carry = 0;
int decimalNum = this.decimal.length();
for (int i = decimalNum - 1; i >= 0; i --) {
char c1 = this.decimal.charAt(i);
char c2 = RHS.decimal.charAt(i);
int tempSum= (c1 - 48) - (c2 - 48) - carry;
carry = tempSum/ 10;
int sumDigit = tempSum % 10;
sum.decimal = (char) (sumDigit - 48) + sum.decimal;
}
sum.whole = "";
int wholeNum = this.whole.length();
for (int i = wholeNum - 1; i >= 0; i --) {
char c1 = this.whole.charAt(i);
char c2 = RHS.whole.charAt(i);
int tempSum = (c1 - 48) - (c2 - 48 ) + carry;
carry = tempSum / 10;
int sumDigit = tempSum % 10;
sum.whole = (char) (sumDigit + 48) + sum.whole;
}
if (carry != 0)
sum.whole = "1" + sum.whole;
return sum;
}
}
take both the numbers as strings and store the signs into the sign string into the corresponding Numbers objects and call your method like
System.out.println("Please enter the first number: ");
firstNumber = kbd.nextString();
System.out.println("Next, enter the second number: ");
secondNumber = kbd.nextString();
Number x = new Number (firstNumber.substring(1),firstNumber.charAt(0));
Number y = new Number (secondNumber.substring(1),secondNumber.charAt(0));
/*convert the firstNumber.substring(1) and secondNumber.substring(1) to doubles using Double.parseDouble()*/
public String doTheOperation(Number other){
if(this.sign.equals(otherNumber.sign)){
/*simply the double values and put the sign*/ in front of it and return it
}
else{
do the simple double subtraction and by looking at your code i believe you can find out the bigger double among them
}
}

nested for() loops && using the "i" count from the first loop in the second so i loops just once using the value?

i am trying to not import the math class to use but i am still trying to estimate the constant "e". it is said e= 1+(1/1!)+(1/2!)+(1/3!)+(1/4!)+(1/5!)+.....
these are what i have int at the top
String userInput;
int uIp; // this converts the string into int type
double e = 2;
then i ask some questions then i check to see not zero to exit and non negative to continue
While(uIp >0){
final int endTheLoop = 15;
int factorialNumber = 1;
double e2TheUserInput=0;
for(int i = 2; i < endTheLoop; i++){
for(int j = 1; j < i; j++){
factorialNumber = ((i - 1) * factorialNumber);
}
e = (1/factorialNumber) + e;
e2TheUserInput = Math.pow(e,uIp);
}
}
You are doing integer division(but e is a double right?):
e = (1/factorialNumber) + e;
Correct that to:
e = (1.0/(double)factorialNumber) + e;
It was counting all the loops, but changes are zero according to the integer division. :)
e= 2+(0)+(0)+(0)+(0)+.....
I am not sure what your code is trying to do but if you want to compute exp(x) this is how I would do it.
public static void main(String... args) {
for (int i = -4; i <= 4; i++)
System.out.println(i + ": " + exp(i) + " cf " + Math.exp(i));
}
private static double exp(double d) {
if (d < 0)
return 1 / exp(-d);
double e = 1, term = 1;
for (int i = 1; i < 20 || term > e * 1e-16; i++) {
term *= d / i;
e += term;
}
return e;
}
For large exponents, it more efficient to evaluate the integral powers without using a taylor series.
public static final double E = 2.7182818284590452354;
private static double exp(double d) {
if (d < 0)
return 1 / exp(-d);
long num = (long) d;
double numE = 1;
double mult = E;
while (num > 0) {
if ((num & 1) != 0)
numE *= mult;
num >>>= 1;
mult *= mult;
}
double fract = d - (long) d;
double fractE = 1, term = 1;
for (int i = 1; i < 20; i++) {
term *= fract / i;
fractE += term;
}
return numE * fractE;
}

Categories

Resources