A leetcode problem (https://leetcode.com/problems/reverse-integer/description/) asks to reverse an integer, which is simple enough, but wants the user to return 0 if there is any overflow. Doing this with long is also simple, as you can check if it's greater than INTEGER.MAX_INT or MIN_INT in java. But if only 32 bit ints are allowed, how can this be accomplished?
The following solution is shown:
public int reverse(int x)
{
int result = 0;
while (x != 0)
{
int tail = x % 10;
int newResult = result * 10 + tail;
if ((newResult - tail) / 10 != result)
{ return 0; }
result = newResult;
x = x / 10;
}
return result;
}
I'm confused why this works. Why does "reversing" the operation, and comparing it to the previous result successfuly check for overflow?
If you started with x, then said:
x2 = (x*10) + b, wouldn't (x2-b)/10 always equal x? Since a positive overflow always loops around to the min value, and a negative overflow always loops around to the max value. How does this check for overflow? I would love any clarifications on this.
If you started with x, then said: x2 = (x*10) + b, wouldn't (x2-b)/10 always equal x?
No. Your intuition about "looping" is correct for addition and subtraction - it's like moving back and forth on a clock face around 12 o'clock.
However, this doesn't apply to multiplication, as this example demonstrates:
int x = 2_000_000_000;
int y = x * 10;
int z = y / 10;
System.out.println(x); // 2000000000
System.out.println(z); // -147483648
Live demo.
So to answer the top-level question:
Why does "reversing" the operation, and comparing it to the previous result successfully check for overflow?
Because when overflow occurs, "reversing" this sequence of operations won't get you back to the input value.
Related
For this formula:
I had to make a method to automate it, and I've received 4 examples to try it out.
x = 1 > p = 2
x = 3 > p = -226
x = 4 > p = 9854
however, when I insert 11 the answer should be 3.0198773447 and I receive -1.78316945E8 instead :/
here is my code:
System.out.println("Insira o numero: ");
int x = input.nextInt();
int fat = 1;
int contador = 0;
int contador1 = 0;
double p = 0;
for(double i = 1; i <=x; i++){
fat = 1;
contador++;
contador1 = contador* 2;
for(double j = 1; j <= contador1; j++){
fat *=j;
}
if(contador <=1){
p += fat / contador;
}
if(contador % 2 ==0 && contador > 1){
p += fat / contador;
}else if( contador % 2 != 0 && contador > 1){
p -= fat / contador;
}
}
System.out.println(p);
If you type in 11, that means contador1 will become as high as 22 (you will loop 11 times, every loop you first increment contador, and contador1 is twice that, so, 22. In other words, you'll end up having to calculate 22!.
The int type does not hold any arbitrary integer. It can only hold integers between -2^31 and +2^31-1. If you try to go beyond those bounds, it just loops around. Witness it in action:
int x = Integer.MAX_VALUE; // a constant representing 2^31-1.
int y = x + 1;
System.out.println(x);
System.out.println(y);
// Prints: 2147483647
// -2147483648
Where'd that minus come from? That's that whole 'loops around' thing. 22! is much lager than than this upper bound. Hence, your code doesn't work and it also explains why your algorithm tosses a negative number in there.
You could choose to use long instead which can hold it, but long, too, has limits - 2^63-1 to be precise. You could use double which goes ever further (up to about 1e308 which is a lot more than 2^63), but doubles are not accurate and the lack of accuracy gets worse as you move further away from 0. Past 2^53 or so, the distance between 2 representable numbers in the double range is more than 1, meaning, +1 no longer does anything (all operations on double values are rounded to the nearest representable double after every operation).
More generally trying to do 'math' on really large numbers is a non-trivial affair, and your basic + and / can no longer get the job done. Look up the API of BigDecimal which guarantees you perfect accuracy at the cost of, naturally, performance. You could use that, and get perfect answers. Though it'll take a while.
I need a method in java which returns a solve for an equation this equation without code is like this :
get a number(Z)
and an angle(C) in radians
then find the value of X which is the solution for this equation:
a = Integer( z*cos(c) ) // temp must be integer
//now we have the value of a
// we put it in b
b = a
//now we look for the value of x that solves this equation
b =? Integer( X/cos(C) ) // X also must be integer
X = ?? // we must get X the solves the equation above
Example: consider
Z = 15
C = 140 // full angles will be casted ..it will be rooted to ~-0.0629*PI
temp = Integer( 15*cos(140) // -2.96 )
temp <-- -2 //after parsing to integer
-2 = Integer ( X )/cos(140)
what is X ?
I tried to implement this method in java but most of the times it stuck finding a result
this code doesn't find a direct solution like i want it tests numbers till it gets it but in many of times it can't find a result and keeps looping to the infinity . Also it is so slow in finding the result and i call that function more than 500,000 times in the program
int Rounding(int z, int c){
int offset = 20 ;
int x;
int test = (int) ( z*Math.cos(c) - offset );
int solution;
while(true){
solution = (int) ( test/Math.cos(c) );
if(solution == z){
x = solution;
break;
}else{
test++;
}
/*
if(solution > z){
offset ++;
solution = (int) ( z*Math.cos(c) - offset );
}
*/
}
return x;
}
/*Note : the function will return x only when it solves this : */
int returned_Z = (int) ( x/Math.cos(c) )
// returned_Z must be equal to z
After that that variable x will be stored in a file ...
then when the file opens this variable x will be returned to z with this function :
int returning(int x, int c){
int z = (int) ( x/Math.cos(c) );
return z;
}
From your posting, we have
temp = Integer( 15*cos(140) // -2.96 )
Find X such that
temp = Integer ( X/cos(140) )
We can solve this for X without the integer conversions.
X = 15 / cos^2(140)
or, in general
X = Z / cos^2(C)
This will give you an exact solution for X; you may apply the integer intermediate requirement if needed for some other purpose.
Update per OP comment
You have a defined mathematical relationships between X, temp, and Z. Truncating the intermediate result breaks some of that relationship. In short, if you restrict X to integers, you cannot guarantee that you get exactly Z when you apply the inverse operations.
In particular, you have a transcendental function cos; you cannot dictate that it will be the ratio of your integers temp and X or X and Z. There do exist point solutions for cos that are known rational numbers, but very few.
If I misunderstand the problem -- I realize that we have some translation problem -- then please update your question to specify the correct problem.
Actually the eqn has infinite number of solutions. Say temp = 2. And you write:
2 = Integer ( ( X )/cos(140) )
If we take Integer() for all real numbers in the range 2.0 <= num < 3.0, it results in 2. That's why infinite number of solutions possible. For example, if we take 2.5 from the range:
2 = Integer (2.5) is true
so we can write,
x / cos(140) = 2.5
=> x = 2.5 * cos(140)
= −1.915111108
If we take another 2.3 from the range:
x = −1.761902219
Since there infinite number of real numbers in the range 2.0 <= num < 3.0, the number of solutions is infinite too.
So you can't just expect a single solution for x. If you do, then use:
int Rounding(int z, int c){
int test = ( z*Math.cos(c) );
int x = (int) ( test*Math.cos(c) );
return x;
}
This will give you a correct answer. But as I said before, there are infinite number of solutions for x.
I am currently working on a Java math library which will include a variety of correctly rounded functions (i.e. sqrt, cbrt, exp, sin, gamma, and ln). I have already used the Babylonian method to write a square root algorithm that is correct to within 1 ulp of the correct answer. However, I cannot figure out how to properly calculate which way the number should be rounded to represent the best possible approximation to the actual square root of the input. Answers containing principles which can be extended to other functions would be preferred, but I have heard that sqrt is a simpler case than many transcendental functions, and specialized solutions would also be much appreciated.
Also, here is a cleaned-up version of my code as of this question's original submission:
public static double sqrt(double x) {
long bits = Double.doubleToLongBits(x);
// NaN and non-zero negatives:
if (Double.isNaN(x) || x < 0) return Double.NaN;
// +-0 and 1:
if (x == 0d || x == 1d) return x;
// Halving the exponent to come up with a good initial guess:
long exp = bits << 1;
exp = (exp - 0x7fe0000000000000L >> 1) + 0x7fe0000000000000L >>> 1 & 0x7ff0000000000000L;
double guess = Double.longBitsToDouble(bits & 0x800fffffffffffffL | exp);
double nextUp, nextDown, guessSq, nextUpSq, nextDownSq;
// Main loop:
while (true) {
guessSq = guess * guess;
if (guessSq == x) return guess;
nextUp = Math.nextUp(guess);
nextUpSq = nextUp * nextUp;
if (nextUpSq == x) return nextUp;
if (guessSq < x && x < nextUpSq) {
double z = x / nextUp;
if (z * nextUp > x) z = Math.nextDown(z);
return z < nextUp ? nextUp : guess;
}
nextDown = Math.nextDown(guess);
nextDownSq = nextDown * nextDown;
if (nextDownSq == x) return nextDown;
if (nextDownSq < x && x < guessSq) {
double z = x / guess;
if (z * guess > x) z = Math.nextDown(z);
return z < guess ? guess : nextDown;
}
// Babylonian method:
guess = 0.5 * (guess + x / guess);
}
}
As you can see, I was using division as a test. However, I believe that requires the division to round towards 0, which obviously doesn't happen in Java.
By the Taylor theorem, the square root function is locally approximated by a linear function, of slope 1/2√x, which is positive. So you can relate the error to the error in the square, x - (√x)², where √x is understood to be the approximate root. Then you round in the direction that minimizes this error.
Anyway, the computation of x - (√x)² is subjected to catastrophic cancellation and you may need extended accuracy to compute it reliably. Not sure the benefit is worth the effort.
I have to divide two numbers by just using the bitwise operators. My code is as follows:
public class Solution {
public int divide(int dividend, int divisor) {
int c = 0, sign = 0;
if (dividend < 0) {
dividend = negate(dividend);
sign^=1;
}
if (divisor < 0) {
divisor = negate(divisor);
sign^=1;
}
if ( divisor != 0){
while (dividend >= divisor){
dividend = sub(dividend, divisor);
c++;
}
}
if (sign == 1){
c = negate(c);
}
return c;
}
private int negate(int number){
return add(~number,1);
}
private int sub(int x, int y){
return add(x,negate(y));
}
private int add(int x, int y){
while ( y != 0){
int carry = x&y;
x = x^y;
y = carry << 1;
}
return x;
}
}
I am getting a time out exception while running the code :
Last executed input:
2147483647
1
I added an extra check in the code like this :
if (divisor == 1){
return dividend;
}
but then on running the code again, I am getting a Time out exception like this:
Last executed input:
2147483647
2
Can you help me where I am going wrong with the code?
Since you are using a naïve implementation of the arithmetical operations, I assume it just takes too long, since it has to do roughly 1 billion of subtractions, each of which is a loop of 16 iterations on average. So it'd be about 5 seconds on a 3GHz CPU, if every inner step took 1 cycle. But since it obviously takes more, especially considering it's in java, I'd say you can easily expect something like a 1 minute running time. Perhaps java has a timeout check for the environment you are running it in.
I have to admit I haven't thoroughly verified your code and assumed it worked correctly algorithm-wise.
Think of how long division works, the pen-and-paper method for division we've all learnt at school.
Of course we've learnt it in base 10, but is there any reason why the same algorithm wouldn't work in base 2?
No, in fact it's easier because when you're doing the division step for each digit, the result is simply 1 if the part of the dividend above the divisor is greater than or equal to the divisor, and 0 otherwise.
And shifting the divisor and the result come out of the box too.
I need help writing a program that uses binary search to recursively compute a square root (rounded down to the nearest integer) of an input non-negative integer.
This is what I have so far:
import java.util.Scanner;
public class Sqrt {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter A Valid Integer: ");
int value = console.nextInt();
calculateSquareRoot(value);
}
public static int calculateSquareRoot(int value) {
while (value > 0) {
double sqrt = (int) Math.sqrt(value);
System.out.println(sqrt);
}
return -1;
}
}
The fact that it has to use binary search to compute the square root is the part that is confusing me. If anyone has any suggestions on how to do this, it would be greatly appreciated. Thank you
Teh codez:
def sqrt(n):
low = 0
high = n+1
while high-low > 1:
mid = (low+high) / 2
if mid*mid <= n:
low = mid
else:
high = mid
return low
To understand it, just think of the loop invariant, namely:
lowlow <= n < highhigh
If you understand this code, writing a recursive version should be trivial.
You can use this java method (Iterative)
public class Solution {
// basic idea is using binary search
public int sqrt(int x) {
if(x == 0 || x == 1) {
return x;
}
int start = 1, end = x / 2;
while(start <= end) {
int mid = start + (end - start) / 2;
if(mid == x / mid) {
return mid;
}
if(mid < x / mid) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return start - 1;
}
}
You can drive your own recursive method
Essentially the idea is that you can use binary search to get closer to the answer.
For example, say you are given 14 as an input. Then, you are sure that the square root of 14 is between 0 and 14. So, 0 and 14 are your current "boundaries". You bisect these two end points and obtain the mid point: 7. Then you try 7 as a candidate - If the square of 7 is greater than 14, then you have a new boundary (0,7); otherwise you would have a new boundary (7,14).
You keep repeating this bisection until you are "close enough" to the answer, for example you have a number square of which is within 14-0.01 and 14+0.01 - then you declare that as the answer.
OK, that much hint should be good enough for HW. Don't forget to cite StackOverflow.
I'm assuming this is homework so I'm only going to give a hint.
To conduct a binary search, you pick a point as close as possible the median of possible correct values. So the question becomes what is a typical median value for a square root, that is either constant or can be computed via multiplication. Obviously using an arbitrary constant will not work for most inputs, so you need to arrive at your guess by multiplying the input by a constant.
As for what that constant C to multiply by should be, that should be chosen based on what values you expect as input. For example, if you expect your inputs to be around 250,000, then:
C * 250,000 ~= sqrt(250,000)
C = sqrt(250,000) / 250,000
C = 500 / 250,000
C = 1 / 500
I see two important computing concepts in your question. The first is binary search, the second is recursion. Since this is homework, here is a contribution towards understanding a binary search, recursion and how to think about them.
Think of binary search as dividing the solution "space" in half, keeping the half the solution is in and doing that in succession so that the process converges on the solution. The key concepts for doing this are that you need to engineer a solution "space" that has the following properties:
1) can be subdivided, usually in half or at least two pieces
2) of the two pieces after subdivision, there is a way to determine which half has the solution so that the process can be repeated on only one half.
Recursion involves a function (method in O-O speak) invoking itself. Recursion works really well for a process that converges to a conclusion. It either recurses forever or until you run out of some resource, usually memory, and it fatally stops. The two key concepts for recursion are:
1) convergence through some invariance (more on invariance below).
2) termination condition (one that recognizes sufficient convergence).
Now, for your square root routine. The requirements for the routine are:
1) Integer input.
2) Integer square-root approximation that gives the floor integer closest to the actual square root.
3) Use recursion.
4) Use binary search.
It helps to know some mathematics about square roots for this. Elementary calculus and analytical geometry concepts are helpful too. Lets do some reasoning.
We have an arbitrary positive integer x. We want its root y. If we choose some test value for y, we can see if it is the root of x if y * y = x. If y is too big, y * y > x. if y is too small, y * y < x. We also know that 0 <= root <= x and that square-roots of 0 and 1 are trivially zero and 1. Since we are looking for largest integer where y * y <= x (i.e. a floor value) we'll have to account for that too.
Here is some mathematical reasoning to help. We know that x = y * y where y is the square root of x. That means: y = x/y.
Hmmm... what happens if y is to large to be the square root of x? Then: x < y * y and: x/y < y which means x/y is also too small to be the square root of x. So we know that, for y too large, x/y < square-root of x < y. So, lets find a new y, say y1, between x/y and y as a new test value. The average of x/y and y will do. y1 = (x/y0 + y0)/2 will give a y1 that is closer to the square root of x than y0 if y0 is too large.
Does this converge? Well, in mathematics using positive real numbers, the average will always be above the value but getting closer each iteration. This satisfies the condition that we successively divide the solution "space" into two parts and know which of the two to keep. In this case, we successively calculate new values below previous ones and below which the answer still lies, allowing us to discard all values above the new one. We stop when we reach a condition where no more new values above the answer exist. Using computers, however, results in binary approximations of real numbers. With integers, there is truncation in division. This may affect the convergence beneficially or adversely. In addition, your answer is supposed to be the largest integer smaller than or equal to the square root. It's wise to take a look at the kind of convergence we will get.
Because of integer division turncation, y1 = (x/y0 + y0)/2 will converge until successive iterations reach an integer root or a floor value for (i.e. the largest integer less than) the root. This is ideal. If we start with a proposed value for the root that has to be larger than the root, say x itself, the first value for yn where yn * yn <= x is the desired result.
The simple answer is that, when we start with y0 > y, the first new yn that is less than or equal to y, then y - yn < 1. That is, yn is now the floor value for which we've been looking and we now have a termination condition that exactly satisfies the conditions for the required answer.
Here are basic iterative and recursive solutions. The solutions don't incude safety features to ensure negative values are not input for x. The one major concern is to avoid dividing by zero in case someone wants to find the square root of 0. Since that is a trivial answer, both the recursive and iterative methods return 0 before division by zero can take place. Both the recursive and iterative solutions work with the trivial cases for finding the square roots of 0 and of 1.
There is another analysis that always has to be done with int and long arithmetic in Java. A major concern is integer overflow since Java does nothing about int or long overflow. Overflow results in twos-complement values (look that up elsewhere) that can lead to bogus results and Java does not throw exceptions with int or long overflow.
In this case, it is easy to avoid arithmetic that could result in an internal overflow with large values of x. If we create a termination condition such as y0 * y0 < x we risk overflow if x is greater than the square root of Integer.MAX_VALUE since y0 * y0, an intermediate value, will immediately exceed the maximum int value. However, we can rearrange the termination condition to y0 < x / y0. We still have a problem with the calculations: ((x / y0) + y0) / 2) if x and y0 are Integer.MAX_VALUE since it wll attempt Integer.MAX_VALUE + 1. However, we can always start with a value less than x that is guaranteed to be > y. x / 2 works for all values of x > 1. Since the square root of x where x is either 0 or 1 is simply x, we can easily test for those values and simply return the correct and trivial value. You can construct code to prevent using values < 0 or values > Integer.MAX_VALUE. The same can be applied if we use long instead of int. Welcome to computing in the real world!
public static int intSqRootRecursive (int x) {
// square roots of 0 and 1 are trivial and x / 2 for
// the y0 parameter will cause a divide-by-zero exception
if (x == 0 || x == 1) {
return x;
}
// starting with x / 2 avoids overflow issues
return intSqRootRecursive (x, x / 2);
} // end intSqRootRecursive
private static int intSqRootRecursive(int x, int y0) {
// square roots of 0 and 1 are trivial
// y0 == 0 will cause a divide-by-zero exception
if (x == 0 || x == 1) {
return x;
} // end if
if (y0 > x / y0) {
int y1 = ((x / y0) + y0) / 2;
return intSqRootRecursive(x, y1);
} else {
return y0;
} // end if...else
} // end intSqRootRecursive
public static int intSqRootIterative(int x) {
// square roots of 0 and 1 are trivial and
// y == 0 will cause a divide-by-zero exception
if (x == 0 || x == 1) {
return x;
} // end if
int y;
// starting with y = x / 2 avoids overflow issues
for (y = x / 2; y > x / y; y = ((x / y) + y) / 2);
return y;
} // end intSqRootIterative
You can test the recursive solution to find out how many instances will result on the frame stack, but you will see that it converges very fast. It's interesting to see that the iterative solution is much smaller and faster than the recursive one, something that is often not the case and is why recursion gets used where it can be predicted that stack resources are sufficient for the recursion depth.
Here is the recursive solution in Java using binary search :
public class FindSquareRoot {
public static void main(String[] args) {
int inputNumber = 50;
System.out.println(findSquareRoot(1, inputNumber, inputNumber));
}
public static int findSquareRoot(int left, int right, int inputNumber){
// base condition
if (inputNumber ==0 || inputNumber == 1){
return inputNumber;
}
int mid = (left + right)/2;
// if square of mid value is less or equal to input value and
// square of mid+1 is less than input value. We found the answer.
if (mid*mid <= inputNumber && (mid+1)*(mid+1) > inputNumber){
return mid;
}
// if input number is greater than square of mid, we need
// to find in right hand side of mid else in left hand side.
if (mid*mid < inputNumber){
return findSquareRoot(mid+1, right, inputNumber);
}
else{
return findSquareRoot(left, mid-1, inputNumber);
}
}
}
Iterative binary solution:
public static double sqrt(int n) {
double low = 0;
double high = n;
double mid = (high - low) / 2;
while (Math.abs((mid * mid) - n) > 0.000000000001) {
if ((mid * mid) > n) {
high = mid;
mid = (high - low) / 2;
} else{
low = mid;
mid = mid + ((high - low) / 2);
}
}
return mid;
}
edst solution is good, but there is a mistake in line 11:
mid = (high - low) / 2;
should be
mid = low + (high - low) / 2;