Related
I have to multiply two large numbers like x and y and then find the mod of result by p without using BigIntegerlike :
public static char[] x = {'1','1','5','7','9','2','0','8','9','2','3','7','3','1','6','1','9','5','4','2','3','5','7','0','9','8','5','0','0','8','6','8','7','9','0','7','8','5','3','2','6','9','9','8','4','6','6','5','6','4','0','5','6','4','0','3','9','4','5','7','5','8','4','0','0','7','9','0','8','8','3','3','7','6','6','4','4','7'};
public static char[] y = {'1','1','5','7','9','2','0','8','9','2','3','7','3','1','6','1','9','5','4','2','3','5','7','0','9','8','5','0','0','8','6','8','7','9','0','7','8','5','3','2','6','9','9','8','4','6','6','5','6','4','0','5','6','4','0','3','9','4','4','3','7','4','8','7','3','8','7','4','7','3','1','9','0','6','9','7','4','3'};
public static char[] p = {'1','1','5','7','9','2','0','8','9','2','3','7','3','1','6','1','9','5','4','2','3','5','7','0','9','8','5','0','0','8','6','8','7','9','0','7','8','5','3','2','6','9','9','8','4','6','6','5','6','4','0','5','6','4','0','3','9','4','5','7','5','8','4','0','0','7','9','0','8','8','3','4','6','7','1','6','6','3'};
I find out how to multiply x and y but I don't know how to compute mod of two large numbers
Can anyone help me?
Can you compare x and y?
If you can compare them, you can easily implement mod algorithm.
Pseudo Code
function mod(a , b) {
while( a > b ) { a = a - b; }
return a;
}
I dont know java, this is just pseudo code for algorithm.
But if you have implemented subtract and compare functions, you can use them here.
Is there a Java function to convert a positive int to a negative one and a negative int to a positive one?
I'm looking for a reverse function to perform this conversion:
-5 -> 5
5 -> -5
What about x *= -1; ? Do you really want a library function for this?
x = -x;
This is probably the most trivial question I have ever seen anywhere.
... and why you would call this trivial function 'reverse()' is another mystery.
Just use the unary minus operator:
int x = 5;
...
x = -x; // Here's the mystery library function - the single character "-"
Java has two minus operators:
the familiar arithmetic version (eg 0 - x), and
the unary minus operation (used here), which negates the (single) operand
This compiles and works as expected.
Another method (2's complement):
public int reverse(int x){
x~=x;
x++;
return x;
}
It does a one's complement first (by complementing all the bits) and then adds 1 to x. This method does the job as well.
Note: This method is written in Java, and will be similar to a lot of other languages
No such function exists or is possible to write.
The problem is the edge case Integer.MIN_VALUE (-2,147,483,648 = 0x80000000) apply each of the three methods above and you get the same value out. This is due to the representation of integers and the maximum possible integer Integer.MAX_VALUE (-2,147,483,647 = 0x7fffffff) which is one less what -Integer.MIN_VALUE should be.
Yes, as was already noted by Jeffrey Bosboom (Sorry Jeffrey, I hadn't noticed your comment when I answered), there is such a function: Math.negateExact.
and
No, you probably shouldn't be using it. Not unless you need a method reference.
original *= -1;
Simple line of code, original is any int you want it to be.
Necromancing here.
Obviously, x *= -1; is far too simple.
Instead, we could use a trivial binary complement:
number = ~(number - 1) ;
Like this:
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
int iPositive = 15;
int iNegative = ( ~(iPositive - 1) ) ; // Use extra brackets when using as C preprocessor directive ! ! !...
System.out.println(iNegative);
iPositive = ~(iNegative - 1) ;
System.out.println(iPositive);
iNegative = 0;
iPositive = ~(iNegative - 1);
System.out.println(iPositive);
}
}
That way we can ensure that mediocre programmers don't understand what's going on ;)
The easiest thing to do is 0- the value
for instance if int i = 5;
0-i would give you -5
and if i was -6;
0- i would give you 6
You can use the minus operator or Math.abs. These work for all negative integers EXCEPT for Integer.MIN_VALUE!
If you do 0 - MIN_VALUE the answer is still MIN_VALUE.
For converting a negative number to positive. Simply use Math.abs() inbuilt function.
int n = -10;
n = Math.abs(n);
All the best!
In kotlin you can use unaryPlus and unaryMinus
input = input.unaryPlus()
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/unary-plus.html
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/unary-minus.html
You can use Math:
int x = Math.abs(-5);
I'm doing some small program for a beginners programming course and in my program I have 2 variables which hold numbers. Anyway I need to find out which number is bigger and print the appropriate message according to it, for example I have:
int x = 5;
int y = 10;
I need to print:
"it is true that y is bigger than x";
Now the thing is that I know I can use a simple if statement but I'm not allowed to use it, now it makes me wonder, is it even possible? If so, how can I do that? How can I check which number is bigger WITHOUT doing something like:
if (x > y)
answer = true;
...
Thanks in advance.
Well you can do:
boolean answer = x > y;
The expression x > y is just an expression of type boolean. While boolean expressions are often used for conditions in if statements, loops etc, they don't have to be - simple assignment works fine too.
It sounds like you want the reverse though:
boolean answer = y > x;
Then you can use the value of answer to build the string to display...
Use the ternary operator:
System.out.println(x > y ? "It is true that x is greater than y" : "");
ternary operator "?:"
String output = (x > y)? "x is greater than y":"y is greater than x";
The ternary conditional operator that others mentioned will work. Assuming you are looking for creative ways to do this rather than practical ones, here's another method:
int x = 5;
int y = 10;
while(y > x){
System.out.println("It is true that y is bigger than x.");
return;
}
System.out.println("It is false that y is bigger than x.");
The while is just acting as a fancy if, because the return means the otherwise infinite loop will only execute at most once.
Here's another example that instead relies upon short-circuit boolean evaluation:
public static void main(String...args){
int x = 5;
int y = 10;
boolean answer = (y > x);
boolean testTrue = answer && printTrue();
boolean testFalse = testTrue || printFalse();
}
private static boolean printFalse() {
System.out.println("It is false that y is bigger than x.");
return true;
}
private static boolean printTrue() {
System.out.println("It is true that y is bigger than x.");
return true;
}
Of course you shouldn't do this in real production code, but it can be fun to think of unorthodox ways to code something and it can be helpful for exploring the language.
Your question is tagged as Java but you do not specify Java in your question. In Java there are multiple ways to get the same result that involve testing the boolean expression x > y somehow, such as the ternary operator. I would consider these equivalent to an explicit if statement.
Other possibilities:
Compute the square root of x - y. This will raise an exception if y is bigger. Catch the exception in the caller and report that y is the larger quantity. If there is no exception, report that x is the larger.
In LISP, Ruby or another language that supports the symbol type, form a list ((symbol x, x), (symbol y, y)) and sort the list. Then report the second symbol as the variable with the larger value.
If using assembly, BASIC, PL/1, etc. you can use an arithmetic expression to choose the target of a GOTO statement. Depending on whether x or y is larger, execution will resume at a different part of the code. Or use the list-sorting trick in the previous bullet to select the GOTO label.
In general, the expression ((x - y) / abs(x - y) + 1) / 2 will produce 1 if x is larger and 0 if y is larger. This result could be used to choose data, a function, etc. out of a list of two alternatives, producing conditional behavior without an if statement.
You could use recursion (but I would not recommend it)
public int compare ( int a , int b )
{
switch ( a )
{
case Integer.MIN_VALUE :
switch ( b )
{
case Integer.MIN_VALUE :
return 0 ;
default :
return -1 ;
}
default :
switch ( b )
{
case INteger.Min_VALUE :
return 1 ;
default :
return compare ( a-1 , b-1 ) ;
}
}
}
(a+b)/2 + Abs(a-b)/2 is the bigger number.
I know in some languages you can use short-circuit evaluation to construct the answer.
The expression (A && B) always evaluates to B if A is true. If A is false then B is never evaluated.
Similarly (A || B) evaluates to B if A is false. If A is true B is never evaluated.
Though I'm not 100% sure of Java, the expression you want is:
String output = ((x > y) && "it is true that X is greater than Y")
|| (((x < y) && "it is true that X is less than Y")
|| "it is true that X is equal to Y");
Is quaternion comparison possible? I'm writing a Java class of Quaternions and I want to implement the Comparable interface to use the Collections.sort(List<Quaternion>) facility. I'm not expert at math, I really don't understand the things I read about Quaternions. So, can anyone tell me can I override the compareTo method for Quaternions and how?
My class declarition:
public class Quaternion implements Serializable, Comparable<Quaternion> {
private double s; // scalar part
private double i, j, k; // vectorel part
public Quaternion() {
super();
}
public Quaternion(double s, double i, double j, double k) {
super();
this.s = s;
this.i = i;
this.j = j;
this.k = k;
}
You can implement compareTo, by comparing its fields. However, you need to determine what you want the order to be like. AFAIK, there is no standard definition of what comes before or after for complex numbers let alone a quaternion.
You certainly can compare them; whether the comparison is meaningful or not is open to debate. Since a quaternion can represented by four real numbers, you'd just do something like (pseudocode)
if (q1.a != q2.a)
return q1.a - q2.a;
else if (q1.b != q2.b)
return q1.b - q2.b;
else if (q1.c != q2.c)
return q1.c - q2.c;
else
return q1.d - q2.d;
Since the values are real numbers, you might use an epsilon-based comparison, and you need to convert small positive and negative differences into positive and negative integers. But you get the idea.
There is no reason why you can't compare two quaternions. Assuming that you want to compare magnitudes, compute and compare the Quaternion Norms. Your Quaternion class should have a norm (magnitude) method allowing a toCompare to be something like the following:
int compareTo(Quaternion o){
return (int)(this.norm() - o.norm());
}
A better version would be:
int compareTo(Quaternion o){
// return (int)(this.norm() - o.norm());
double tNorm = this.norm;
double oNorm = o.norm;
int retVal = 0;
if (tNorm < oNorm){
retVal = -1;
} else if (tNorm > oNorm){
retVal = 1;
}
return retVal;
}
A quaternion is a kind of 4-dimensional vector.
How do you want to order them? The most reasonable way would be to use the norm.
public int compareTo(Object o) {
if (o instanceOf Quaternion) {
// Compute the difference between the square of the norm
double result = s*s + i*i + j*j + k*k - o.s*o.s - o.i*o.i - o.j*o.j - o.k*o.k;
if (result > 0) { return 1; }
if (result < 0) { return -1; }
return 0;
}
}
Note that using the norm will make quaternions of equal length but pointing in different directions equal, and some algorithms will not be able to distinguish between them. Sorting algorithms may well throw away "duplicates". Just a friendly warning.
Think about quaternions as a tuple (ordered list) of four floating-point numbers. Defining equality is pretty straightforward, but how would you define total order? In other words, how do you want to define greater-than relationship between two four-number sequences?
In fact, there is no common greater-than relationship even between complex numbers and quaternions can be considered as a pair of complex numbers. Easy comparison is only possible in one-dimensional space. Complex numbers are two-dimensional, quaternions - four.
You can, but I don't think you should.
The argument is the same as for complex numbers. Given two quaternions, they are either equal or not, there is no way to say which one is greater than the other. The quaternions form a division algebra, which is not ordered (unlike the field of the real numbers for example). The only (reasonable) way, I can think of, comparing two quaternions is by using the norm.
double norm = Math.sqrt(s*s + i*i + j*j + k*k);
In that case you could define, that a quaternion a is greater than a quaternion b iff the norm of a is greater than the norm of b. But that is definitely not a standard definition. I would be careful in making quaternions or complex numbers comparable. However, it depends on your use case. Just take into account, that there is no standard way of sorting such numbers.
See this google search for some good links about comparing complex numbers. The argument for quaternions is basically the same.
Another way to compare quaternions would be to use a lexicographic order.
There is no mathematical standard ordering for quaternions or for complex numbers.
You may nevertheless want to implement the Comparable interface, for conveniently sorting and for storing them in TreeSet and TreeMap collections.
To make clear that the ordering is arbitrary I'd use the lexicographic combination of the components of the quaternion. This also ensures that the ordering is consistent with equals, and that the algorithms work as desired.
For a more natural ordering, for example one that takes the norm into account, you can always explicitly define a comparator.
I have two Numbers. Eg:
Number a = 2;
Number b = 3;
//Following is an error:
Number c = a + b;
Why arithmetic operations are not supported on Numbers? Anyway how would I add these two numbers in java? (Of course I'm getting them from somewhere and I don't know if they are Integer or float etc).
You say you don't know if your numbers are integer or float... when you use the Number class, the compiler also doesn't know if your numbers are integers, floats or some other thing. As a result, the basic math operators like + and - don't work; the computer wouldn't know how to handle the values.
START EDIT
Based on the discussion, I thought an example might help. Computers store floating point numbers as two parts, a coefficient and an exponent. So, in a theoretical system, 001110 might be broken up as 0011 10, or 32 = 9. But positive integers store numbers as binary, so 001110 could also mean 2 + 4 + 8 = 14. When you use the class Number, you're telling the computer you don't know if the number is a float or an int or what, so it knows it has 001110 but it doesn't know if that means 9 or 14 or some other value.
END EDIT
What you can do is make a little assumption and convert to one of the types to do the math. So you could have
Number c = a.intValue() + b.intValue();
which you might as well turn into
Integer c = a.intValue() + b.intValue();
if you're willing to suffer some rounding error, or
Float c = a.floatValue() + b.floatValue();
if you suspect that you're not dealing with integers and are okay with possible minor precision issues. Or, if you'd rather take a small performance blow instead of that error,
BigDecimal c = new BigDecimal(a.floatValue()).add(new BigDecimal(b.floatValue()));
It would also work to make a method to handle the adding for you. Now I do not know the performance impact this will cause but I assume it will be less than using BigDecimal.
public static Number addNumbers(Number a, Number b) {
if(a instanceof Double || b instanceof Double) {
return a.doubleValue() + b.doubleValue();
} else if(a instanceof Float || b instanceof Float) {
return a.floatValue() + b.floatValue();
} else if(a instanceof Long || b instanceof Long) {
return a.longValue() + b.longValue();
} else {
return a.intValue() + b.intValue();
}
}
The only way to correctly add any two types of java.lang.Number is:
Number a = 2f; // Foat
Number b = 3d; // Double
Number c = new BigDecimal( a.toString() ).add( new BigDecimal( b.toString() ) );
This works even for two arguments with a different number-type. It will (should?) not produce any sideeffects like overflows or loosing precision, as far as the toString() of the number-type does not reduce precision.
java.lang.Number is just the superclass of all wrapper classes of primitive types (see java doc). Use the appropriate primitive type (double, int, etc.) for your purpose, or the respective wrapper class (Double, Integer, etc.).
Consider this:
Number a = 1.5; // Actually Java creates a double and boxes it into a Double object
Number b = 1; // Same here for int -> Integer boxed
// What should the result be? If Number would do implicit casts,
// it would behave different from what Java usually does.
Number c = a + b;
// Now that works, and you know at first glance what that code does.
// Nice explicit casts like you usually use in Java.
// The result is of course again a double that is boxed into a Double object
Number d = a.doubleValue() + (double)b.intValue();
Use the following:
Number c = a.intValue() + b.intValue(); // Number is an object and not a primitive data type.
Or:
int a = 2;
int b = 3;
int c = 2 + 3;
I think there are 2 sides to your question.
Why is operator+ not supported on Number?
Because the Java language spec. does not specify this, and there is no operator overloading. There is also not a compile-time natural way to cast the Number to some fundamental type, and there is no natural add to define for some type of operations.
Why are basic arithmic operations not supported on Number?
(Copied from my comment:)
Not all subclasses can implement this in a way you would expect. Especially with the Atomic types it's hard to define a usefull contract for e.g. add.
Also, a method add would be trouble if you try to add a Long to a Short.
If you know the Type of one number but not the other it is possible to do something like
public Double add(Double value, Number increment) {
return value + Double.parseDouble(increment.toString());
}
But it can be messy, so be aware of potential loss of accuracy and NumberFormatExceptions
Number is an abstract class which you cannot make an instance of. Provided you have a correct instance of it, you can get number.longValue() or number.intValue() and add them.
First of all, you should be aware that Number is an abstract class. What happens here is that when you create your 2 and 3, they are interpreted as primitives and a subtype is created (I think an Integer) in that case. Because an Integer is a subtype of Number, you can assign the newly created Integer into a Number reference.
However, a number is just an abstraction. It could be integer, it could be floating point, etc., so the semantics of math operations would be ambiguous.
Number does not provide the classic map operations for two reasons:
First, member methods in Java cannot be operators. It's not C++. At best, they could provide an add()
Second, figuring out what type of operation to do when you have two inputs (e.g., a division of a float by an int) is quite tricky.
So instead, it is your responsibility to make the conversion back to the specific primitive type you are interested in it and apply the mathematical operators.
The best answer would be to make util with double dispatch drilling down to most known types (take a look at Smalltalk addtition implementation)