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.
Related
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.
What is the difference between minus and mod operators in terms of time required for computation? I have noticed that mod takes significantly lesser time than minus. For example -
Problem statement - I'm incrementing a variable 'x' by 1, 'x' should not be greater than 'y'.
This can be done in 2 ways.
1)
if(x > y) x = x - y;
or
2)
if(x > y) x = x % y;
The 2nd approach is faster than 1st. Can anyone please explain?
Here's the code - init, y and hop are inputs, hop is always less than y.
int x = init;
int count = 1;
do{
x += hop;
count++;
if (x > y)
x = x - y;
} while(x != y);
P.S. The code is just an example. I'm not concerned about what it does. I just want to know how using % instead of - reduces the time.
I have this code :
public static int rsnpeasant(int x, int y) {
if ((y & 1) == 0) {
y = y / 2;
x = x * 2;
rsnpeasant(x, y);
} else {
sum = sum + x;
y = y / 2;
y = y - 1 / 2;
x = x * 2;
if (y == 1) {
sum = total;
return total;
} else {
rsnpeasant(x, y);
}
}
total = sum;
return total;
}
The error is happening on the first rsnpeasant(x,y); line in the first if statement. It seems to be forever looping to that line even though it's supposed to go to the else statement if y is odd. If y is divided by 2 it should become odd at some point.
Link is what im trying to code
y=y-1/2...
Order of operations will evaluate the 1/2 and subtract that from y. In integer arithmetic, 1/2 is 0. I think you want y=(y-1)/2.
Your principal problem is that you are trying to divide an int primitive type, if y = 1, dividing that value by 2 will return 0, then you pass it to the method again, it will always be stuck in the first if statement.
You should return a double, float or bigdecimal in your method, and use one of those types for the parameters too.
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.