How to use operators for BigInteger - java

import java.lang.Math;
import java.math.BigInteger;
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) {
int e1 = 20, d = 13;
BigInteger C = BigDecimal.valueOf(e1).toBigInteger();
BigInteger po = C.pow(d);
System.out.println("pow is:" + po);
int num = 11;
BigInteger x = po;
BigInteger n = BigDecimal.valueOf(num).toBigInteger();
BigInteger p, q, m;
System.out.println("x: " + x);
q=(x / n);
p=(q * n);
m=(x - p);
System.out.println("mod is:" + m);
}
}
I've tried looking for some answers related to it but unable to solve. Please can someone tell me what's wrong in this. I changed the datatype to integer but then the power function doesn't works.
this is the error which I get:
error: bad operand types for binary operator '/'
q=(x/n);
^
first type: BigInteger
second type: BigInteger
Main.java:33: error: bad operand types for binary operator '*'
p=(q*n);
^
first type: BigInteger
second type: BigInteger
Main.java:34: error: bad operand types for binary operator '-'
m=(x-p);
^
first type: BigInteger
second type: BigInteger
3 errors
.

Explanation
You can not use the operators on BigInteger. They are not primitives like int, they are classes. Java has no operator overloading.
Take a look at the class documentation and use the corresponding methods:
BigInteger first = BigInteger.ONE;
BigInteger second = BigInteger.TEN;
BigInteger addResult = first.add(second);
BigInteger subResult = first.subtract(second);
BigInteger multResult = first.multiply(second);
BigInteger divResult = first.divide(second);
Operator Details
You can look up the detailed definitions for the operators and when you can use them in the Java Language Specification (JLS).
Here are some links to the relevant sections:
Multiplication * §15.17.1
Division / §15.17.2
String concatenation + §15.18.1
Addition and subtraction + - §15.18.2
Most of them work with the notion of Numeric Type §4, which consists of Integral Type and FloatingPointType:
The integral types are byte, short, int, and long, whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively, and char, whose values are 16-bit unsigned integers representing UTF-16 code units (§3.1).
The floating-point types are float, whose values include the 32-bit IEEE 754 floating-point numbers, and double, whose values include the 64-bit IEEE 754 floating-point numbers.
Additionally, Java can unbox wrapper classes like Integer into int and vice versa, if needed. That adds the unboxing conversions §5.1.8 to the set of supported operands.
Notes
Your creation of BigInteger is unnecessarily long and complicated:
// Yours
BigInteger C = BigDecimal.valueOf(e1).toBigInteger();
// Prefer this instead
BigInteger c = BigInteger.valueOf(e1);
And if possible, you should prefer to go from String to BigInteger and from BigInteger to String. Since the purpose of BigInteger is to use it for numbers that are too big to be represented with the primitives:
// String -> BigInteger
String numberText = "10000000000000000000000000000000";
BigInteger number = new BigInteger(numberText);
// BigInteger -> String
BigInteger number = ...
String numberText = number.toString();
Also, please stick to Java naming conventions. Variable names should be camelCase, so c and not C.
Additionally, prefer to have meaningful variable names. A name like c or d does not help anyone to understand what the variable is supposed to represent.

Arithmetic operations are not working on Objects in Java. However there are already methods to do so like BigInteger#add, BigInteger#divide etc. in BigInteger. Instead of doing
q=(x/n)
you would do
q = x.divide(n);

You can't do operands such as "*","/","+" on objects in Java, if you want these operations you need to do it like this
q = x.divide(n);
p=q.multiply(n);
m=x.subtract(p);

Related

Why System.out.print(ternary operator) print float in output?

I was going through some java interview questions MCQ where I found this code snippet, of which I didn't understand the output, though its only a 2 line code.
int a = 8;
System.out.println(((a<8)? 9.9 : (int)9));
Output is 9.0
I didn't understand why it is not 9 ?
Ternary operator has return type that is defined before the calculation of the value.
So, if the operator can return both float and int, then the both values are upcasted to the float.
Your answer is casted in this way:
(int)9 -> (int)9 -> (float)9.
Other situation: If you add float and int, you get float
int a = 2;
float b = 4.3f;
float c = a + b;
Because you are not casting all of them . you are just casting second result to int.
But don't forget first result is float so all of structure must be same type.
You need to cast all of them as same type like int or float.
int a = 8;
System.out.println(""+ (int)( (a<8)? 9.9 : 9));
output :
9
The return type of the ternary operator is determined according to quite complicated rules:
Java Language Specification. Specifically, in your case:
Otherwise, binary numeric promotion (§5.6.2) is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands.
So in your case you get return type double.

Square Root and ++ Operators for BigInteger and BigDecimal

Is there any ready-made Java library for operations over BigInteger and BigDecimal objects?
I'd like to use square root and ++ operators.
Thank you
P.S. BigInteger.add() should be used instead of ++, I got it.
What about square root from BigInteger?
BigInteger is immutable. That makes something like the ++-operator on it conceptually impossible. You can not change the value of a given BigInteger, just like you can't do it with String.
Incrementing
You always have to create a new BigInteger that holds the incremented value (you can then of course store the reference to that BigInteger in the same variable).
Edit: As pointed out in the comment, "incrementing" would look like:
BigInteger result = a.add(BigInteger.ONE);
or
a = a.add(BigInteger.ONE);
Note that both lines do not change the value of the BigInteger which a originally points to. The last line creates a new BigInteger and stores the reference to it in a.
Calculating the Square
You can calculate the square of a BigInteger like this:
BigInteger a = BigInteger.valueOf(2);
BigInteger a_square = a.multiply(a); // a^2 == a * a
or
BigInteger a_square = a.pow(2);
Square Root
The code is taken from https://gist.github.com/JochemKuijpers/cd1ad9ec23d6d90959c549de5892d6cb .
It uses simple bisection and a clever upper bound. Note that a.shiftRight(x) is equivalent to a / 2^x (only for non-negative numbers, but that is all we deal with, anyway)
BigInteger sqrt(BigInteger n) {
BigInteger a = BigInteger.ONE;
BigInteger b = n.shiftRight(5).add(BigInteger.valueOf(8));
while (b.compareTo(a) >= 0) {
BigInteger mid = a.add(b).shiftRight(1);
if (mid.multiply(mid).compareTo(n) > 0) {
b = mid.subtract(BigInteger.ONE);
} else {
a = mid.add(BigInteger.ONE);
}
}
return a.subtract(BigInteger.ONE);
}
Using Operators Instead of Methods
Operator overloading like in C++ is not possible in Java.

How to divide a BigInteger by integer?

(EDIT: Before more people downvote, I did look at the Javadoc beforehand but since I'm a beginner I wasn't sure where in the document to look. See my response to Jim G, which is posted below. I understand that this question is maybe viewed as too basic. But I think it has some value for other beginners in my situation. So please, consider the full situation from a beginner's perspective before downvoting.)
I want to divide a BigInteger by a regular integer (i.e. int) but I don't know how to do this. I did a quick search on Google and on Stack Exchange but didn't find any answers.
So, how can I divide a BigInteger by an int? And while we're at it, how can I add/subtract BigInts to ints, compare BigInts to ints, et cetera?
Just use BigInteger.valueOf(long) factory method. An int can be implicitly "widened" to be long... This is always the case when going from smaller to large, e.g. byte => short, short => int, int => long.
BigInteger bigInt = BigInteger.valueOf(12);
int regularInt = 6;
BigInteger result = bigInt.divide(BigInteger.valueOf(regularInt));
System.out.println(result); // => 2
Convert the Integer to BigInteger and than divide both BigInteger, as following:
BigInteger b = BigInteger.valueOf(10);
int x = 6;
//convert the integer to BigInteger.
BigInteger converted = new BigInteger(Integer.toString(x));
//now you can divide, add, subtract etc.
BigInteger result = b.divide(converted); //but this will give you Integer values.
System.out.println(result);
result = b.add(converted);
System.out.println(result);
Above division will give you Integer values of divisions, to get exact values, use BigDecimal.
EDIT:
To remove two intermediate variables converted and result in above code:
BigInteger b = BigInteger.valueOf(10);
int x = 6;
System.out.println(b.divide(new BigInteger(Integer.toString(x))));
OR
Scanner in = new Scanner(System.in);
System.out.println(BigInteger.valueOf((in.nextInt())).divide(new BigInteger(Integer.toString(in.nextInt()))));

Why Type Casting of larger variable to smaller variable results in modulo of larger variable by the range of smaller variable

Recently,while I was going through typecasting concept in java, I have seen that type casting of larger variable to smaller variable results in the modulo of larger variable by the range of smaller variable.Can anyone please explain this in detail why this is the case and is it true for any explicit type conversion?.
class conversion {
public static void main(String args[])
{
double a = 295.04;
int b = 300;
byte c = (byte) a;
byte d = (byte) b;
System.out.println(c + " " + d);
}
}
The above code gives the answer of d as 44 since 300 modulo 256 is 44.Please explain why this is the case and also what happens to the value of c?
It is a design decision that goes all the way back the the C programming language and possibly to C's antecedents too.
What happens when you convert from a larger integer type to a smaller integer type is that the top bits are lopped off.
Why? Originally (and currently) because that is what hardware integer instructions support.
The "other" logical way to do this (i.e. NOT the way that Java defines integer narrowing) would be to convert to that largest (or smallest) value representable in the smaller type; e.g.
// equivalent to real thin in real java
// b = (byte) (Math.max(Math.min(i, 127), -128))
would give +127 as the value of b. Incidentally, this is what happens when you convert a floating-point value to an integer value, and the value is too large. That is what is happening in your c example.
You also said:
The above code gives the answer of d as 44 since 300 modulo 256 is 44.
In fact, the correct calculation would be:
int d = ((b + 128) % 256) - 128;
That is because the range of the Java byte type is -128 to +127.
For completeness, the above behavior only happens in Java when the larger type is an integer type. If the larger type is a floating point type and the smaller one is an integer type, then a source value that is too large or too small (or an infinity) gets converted to the largest or smallest possible integer value for the target type; e.g.
double x = 1.0e200;
int i = (int) x; // assigns 'Integer.MAX_VALUE' to 'i'
And a NaN is converted to zero.
Reference:
Java 17 Language Specification: §5.1.3

BigInteger Modulo '%' Operation & Less Than / More Than Operations

Hi I have an algorithm in which I need to apply operations to BigInt's.
I understand that BigInt's can be manipulated using the Maths class such as:
import java.math.*;
BigInteger a;
BigInteger b = BigInteger.ZERO;
BigInteger c = BigInteger.ONE;
BigInteger d = new BigInteger ("3");
BigInteger e = BigInteger.valueOf(5);
a.multiply(b);
a.add(b);
a.substract(b);
a.divide(b);
I need to be able to apply greater than for a while condition e.g.
while (a > 0) {
Which gives me a syntax error saying "bad operand types for binary operator '>', first type: java.math.BigInteger, second type: int.
I also need to be able to apply the modulo (%) operator to a BigInteger.
b = a % c;
Can anyone suggest a way of doing this?
If there isn't a solution then I'm just going to have to somehow manipulate my BigInteger into an unique Long using a reduce function (which is far from ideal).
Silverzx.
To compare BigInteger, use BigInteger.compareTo.
while(a.compareTo(BigInteger.ZERO) > 0)
//...
And for modulo (%), use BigInteger.mod.
BigInteger blah = a.mod(b);
For comparing BigIntegers you may use compareTo, but in the special case when you compare to 0 the signum method will also do the job(and may be a bit faster). As for taking the remainder of a given division you may use the method mod(better option here) or alternatively use divideAndRemainder which returns an array with both the result of the division and the remainder.

Categories

Resources