public static void main(String args[]){
Scanner s = new Scanner(System.in);
int x;
int y;
int z = 0;
x = s.nextInt();
y = s.nextInt();
while(y != 0){
z += x;
y--;
}
System.out.println(z);
}
This is all.
This code calculates x*y but doesn't use *.
It was just a (task ?) somebody told me. And my question is why this is working with negative numbers. That x can be negative is obvious but why can y be.
Edit: I wrote this code on my own so I know why it works without *. That's not the question. I can input 5 for x and -5 for y and i get -25. But why? Everytime he adds one more time x to z y goes 1 down. But after the 5th time it stops.
If you put the "z" print inside the while you will understand.
This code makes overflow. Reach the maximum value that the int permit and decrease again from there
This code makes multiple sums. So it can sum the number 2, 3 times, and thats how it does 2*3.
The y can be negative because the if is seeing != than 0, not < than 0.
Related
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.
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.
Can someone tell me what is this function doing? I just know that it returns the sum of x + y, but I want to know why. Thanks
public static int f(int x, int y){
while( y > 0){
x = x + 1;
y = y - 1;
}
return x;
}
There are two cases:
First case: y <= 0
Because the while loop is false, it just returns x ("it skips the part")
Second case: y > 0
Because the while loop is true, it returns x + y (x + number of iterations)
The number of iterations is the value of y because with every iteration, y will be decreased by 1 until y = 0.
The loop starts at the value of y, and decrements it on each iteration, stopping when y gets to zero.
For each of these iterations, 1 is added to x. Therefore, for 'unit' of y, a 'unit' is added to x.
Edit As noted in the comments, the function will not return the sum of the two numbers if y is less then zero, since the loop will not execute at all.
Addition can be viewed as a series of increments. That's what this function does. It increments x y times and returns the result which is x + y. It is assumed that y is a natural number.
I have a bit of a math puzzler on my hands. I have a random value of X, where X is a double (potentially decimal value) that is 0 < x < 20, and an incremental integer value of Y in a loop that for purposed of this question we will cap at 1000.
I want to reduce the value of X by an incremental percentage based on the current value of Y. Initially I was doing this. getrand() is an external function that returns a NEW value for X on every iteration of the loop.
Integer y = 0;
while (y < 1000)
{
y = y + 1;
Double x = getRand(); // any decimal value between 0 and 20
x = x / y;
// the value of X,Y then gets plotted on a map
doPlot(x,y);
}
While this works, the initial reduction of X is X / 2, then X / 3.. and so on. I would much prefer a linear(ish) or quadratic curve style reduction of X, that starts off as a small reduction of X and becomes larger as Y grows larger, and X should never be negative.
Keep in mind that X could potentially be a decimal value that is < 1. I still want to reduce it by a percentage. I've thought of a number of things I could do, but my code got all filled up with conditional statements to check the value of X.
How can I accomplish this in short and efficient Java? Thanks!
To edify - The X value is a NEW random double between 0 and 20 on EACH iteration of the loop, it is not a static value. X could be 0.00000001 or it could be 19.999999
First of all, that code doesn't do anything. I get that it's just an example, but it doesn't even do what you're talking about, as X is thrown away every iteration.
Anyway, you need to decide how many timesteps you want your iteration to take (since it's linear), and then subtract by the same amount during each iteration of the loop (instead of dividing by a different number each time). Something like:
int timesteps = 10;
double x = getrand();
double subtractEachTime = x/timesteps;
for(int i = 0; i < timesteps; i++)
{
x -= subtractEachTime;
}
Also note that you should make sure x is equal to whatever you actually wanted at the end of the loop, to avoid floating point rounding errors.
This example takes you from a random number down to zero, but it can be generalized to go from any number to any other number. This is called linear interpolation: http://en.wikipedia.org/wiki/Linear_interpolation
It sounds like you dont have a clear picture of what you want to do. Here is a guess at code that will continuously decrease x as a function of (x,i,getRand())
int i = 0;
double x = getrand();
while(true){
double a_number_less_than_one = getRand()/(i+1)*20;
x = x/a_number_less_than_one;
i++;
System.out.println(x);
}
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Is there a difference between x++ and ++x in java?
I am reading the official Java tutorial and I don't get the difference between postfix and prefix (++x vs x++). Could someone explain?
++x: increment x; the value of the overall expression is the value after the increment
x++: increment x; the value of the overall expression is the value before the increment
Consider these two sections:
int x = 0;
System.out.println(x++); // Prints 0
// x is now 1
int y = 0;
System.out.println(++y); // Prints 1
// y is now 1
I personally try to avoid using them as expressions within a larger statement - I prefer standalone code, like this:
int x = 0;
System.out.println(x); // Prints 0
x++;
// x is now 1
int y = 0;
y++;
System.out.println(y); // Prints 1
// y is now 1
Here I believe everyone would be able to work out what's printed and the final values of x and y without scratching their heads too much.
There are definitely times when it's useful to have pre/post-increment available within an expression, but think of readability first.
++x increments x and then returns the value
x++ returns the value of x and then increments the variable
For example:
int x = 0;
int A = ++x; // A = 1
int B = x++; // B = 1
int C = x; // C = 2
Well, you get enough answers, I'm going just to worry you... Both post- and pre-increment operators can confuse code, so sometimes it is better to use just x+1 then you and other people definitely know what is going on there. Some examples:
int x = 5;
x = ++x;
System.out.println( x ); // prints 6
x = x++;
System.out.println( x ); // prints 6!
x = ++x + x++;
System.out.println( x ); // prints 14!
two last incrementing can be a source of problems to debug then (was watching that few times in my life...). x = x++ - it is evaluated before incrementing... So be careful!
++x is pre-incrementing and x++ is post-incrementing. With post-incrementing the value is increased after evaluation and with pre-incrementing the value is increased before evaluation.
Well, standing alone it's the same. but, if there are other operands involved - ++x will advance x and then apply the other operands, and x++ will first use x and then advance it.
Basically, ++x adds 1 to x before x is evaluated, while x++ adds 1 afterwards. It makes sense if you use it as an argument.
Let's start with x
int x = 3;
If we call System.out.println on x using the infix operator:
System.out.println(++x);
x will first increase to 4 and the println will output, "4". It is pretty much the same if we did:
x+=1;
System.out.println(x);
Let's imagine x equals 3 again. If we call System.out.println on x using the postfix operator:
System.out.println(x++);
It will first output the current value of x, "3", and then increase x. So it's like:
System.out.println(x);
x+=1;
Hope that helps.