I have the following code:
public static void main(String[] args) {
int a = 3;
int b = 7;
int x = b; // x=b
int res = a; // res = a
int y = 1;
int invariant = 0;
System.out.println("a|b|x|y|res|invariant");
while (x > 0) {
if (x % 2 == 0) {
y = 2 * y;
x = x / 2;
} else {
res = res + y;
y = 2 * y;
x = (x - 1) / 2;
}
invariant = y + 2;
String output = String.format("%d|%d|%d|%d|%d|%d", a,b,x,y,res,invariant);
System.out.println(output);
}
// < res = a + b >
}
Which gives the following output:
a|b|x|y|res|invariant
3|7|3|2|4|4
3|7|1|4|6|6
3|7|0|8|10|10
However, if I change the numbers, the invariant isn't equal to the res anymore. Therefore my loop invariant for this problem is not correct.
I'm struggling really hard to find the correct loop invariant and would be glad if there's any hint that someone can give me.
My first impression after looking into the code and my results is that the loop invariant changes based on a and b. Let's say both a and b are odd numbers as they are in my example, then my Loop invariant is correct (at least it seems like it)
Is it correct to assume a loop variant like the following?
< res = y - 2 && a % 2 != 0 && b % 2 != 0 >
I did use different numbers and it seems like anytime I change them there's a different loop invariant and I struggle to find any pattern whatsoever.
I would really appreciate if someone can give me a hint or a general idea on how to solve this.
Thanks
This loop computes the sum a+b.
res is initialized to a.
Then, in each iteration of the loop, the next bit of the binary representation of b (starting with the least significant bit) is added to res, until the loop ends and res holds a+b.
How does it work:
x is initialized to b. In each iteration you eliminate the least significant bit. If that bit is 0, you simply divide x by 2. If it's 1, you subtract 1 and divide by 2 (actually it would be sufficient to divide by 2, since (x-1)/2==x/2 when x is an odd int). Only when you encounter a 1 bit, you have to add it (multiplied by the correct power of 2) to the result. y Holds the correct power of 2.
In your a=3, b=7 example, the binary representation of b is 111
In the first iteration, the value of res is a + 1 (binary) == a + 1 = 4
In the second iteration, the value of res is a + 11 (binary) == a + 3 = 6
In the last iteration, the value of res is a + 111 (binary) == a + 7 == 10
You could write the invariant as:
invariant = a + (b & (y - 1));
This takes advantage of the fact the at the end of the i'th iteration (i starting from 1), y holds 2^i, so y - 1 == 2^i - 1 is a number whose binary representation is i 1 bits (i.e. 11...11 with i bits). When you & this number with b, you get the i least significant bits of b.
I ran below program in C++(Dec-c++) :
int k = 5;
k = k++;
cout<<"Value of K :"<<k<<endl;
int l = 5;
l = l++ + l++;
cout<<"Value of L :"<<l<<endl;
int m = 5;
m = m++ + m++ + m++;
cout<<"Value of M :"<<m<<endl;
and got 5,12 and 18 for variables k,l and m.. But same program when I ran in java --
int k = 5;
k = k++;
System.out.println("Value of K :"+k);
int l = 5;
l = l++ + l++;
System.out.println("Value of L :"+l);
int m = 5;
m = m++ + m++ + m++;
System.out.println("Value of M :"+m);
I got 5,11 and 18 for variables k,L and M..
Explain why there is difference in calculations of unary post operators ? I am aware of operator's precedence and priority rules. But every thing fails here. But answer from c++ seems rational according to rules. Confused how java is calculating ?
It's well known C++ and Java are different. Please Suggest how operator-precedence and operator-priority is handled in Java.
The rule for Java is quite simple here. The sub-expressions (each call to the postfix operator) are evaluated left to right, each one being fully evaluated before the next.
int k = 5;
k = k++;
This increments k to 6, but returns its previous value (5) and reassigns that to k. So k is 5.
int l = 5;
l = l++ + l++;
The first l++ increments l to 6, and evaluates to its previous value (5). Then the next l++ is called, which increments l to 7, and evaluates to 6. The 5 and 6 are added together and assigned to l, resulting in 11.
int m = 5;
m = m++ + m++ + m++;
Using the same process as before, we just do it one more time, so this is equivalent to adding 5 + 6 + 7 and assigning the result to m, which becomes 18.
The C++, despite your claim that you understand it, is not so simple. In fact, it is undefined behavior, as thoroughly explained in the answers to this question. There are no rules, and you can see any results whatsoever. Don't do it.
Java says that the result of the following calculation is -24.
But isn't --(-3)*(6)++ == -4*7 == -28?
public int rechnung3()
{
int k = -3;
int i = 6;
return --k*i++;
}
No because the postfix increment happens after the expression has been evaluated. So essentially, the i is only incremented after the result has been stored on the stack.
So what happens is equivalent to something like this:
int k = -3;
int i = 6;
k = k -1; // --k makes k = -4
int tmp = k * i; // a temporary location stores the value of (--k) * i = -24
i = i + 1; // i++ increments i, now i = 7
return tmp; // returns -24 (the result from the auxiliary location)
Your variable k has the "pre-decrement" operator, meaning that the value is reduced before it is used in the calculation. So your -4 is correct. However, the variable i has the "post-increment" operator, meaning that the value is increased after it is used in the calculation. So, the value that is used is 6. If there were any code later in the function (if you did not return immediately), the value would be 7 if you used the variable again.
I'm running this code, but why the output result of m is always zero here?
This is very strange since m is initialized to 2.
public class ScalabilityTest {
public static void main(String[] args) {
long oldTime = System.currentTimeMillis();
double[] array = new double[100000];
int p = 2;
int m = 2;
for ( int i = 0; i < array.length; i++ ) {
p += p * 12348;
for ( int j = 0; j < i; j++ ) {
double x = array[j] + array[i];
m += m * 12381923;
}
}
System.out.println( (System.currentTimeMillis()-oldTime) / 1000 );
System.out.println( p + ", " + m );
}
}
Since you are always multiplying the value of m with a number and add to m, on the 16th iteration it overflows to become 0.
In fact, since you are multiplying the number with an odd number then add it to the original, you are multiplying it with a even number, which make the trailing 0 bits moves at least one step left, thus it ends with 0:
1 1011110011101110111001000 24763848
2 1111011100110010111011000100000 2073654816
3 1111111111111101111010010000000 2147415168
4 10010100011000001100001000000000 -1805598208
5 10010010100010001100100000000000 -1836529664
6 10001011110000100010000000000000 -1950212096
7 1110010101001001000000000000000 1923383296
8 1001100000100000000000000000 159514624
9 1010011110010000000000000000000 1405616128
10 10001110001000000000000000000000 -1910505472
11 1010100100000000000000000000000 1417674752
12 1000010000000000000000000000000 1107296256
13 11001000000000000000000000000000 -939524096
14 100000000000000000000000000000 536870912
15 10000000000000000000000000000000 -2147483648
16 0 0
Here's an observation: as soon as m reaches 0, executing
m += m * 12381923;
Will keep m at 0.
I wrote a program to output the values of m as it goes, and here's what I found:
2
24763848
2073654816
2147415168
-1805598208
-1836529664
-1950212096
1923383296
159514624
1405616128
-1910505472
1417674752
1107296256
-939524096
536870912
-2147483648
0
Converged after 16 iterations.
For reference, here's the source:
public class Converge {
public static void main(String[] args) {
int m = 2;
long counter = 0; // Unnecessary, but I didn't know how many iterations we'd need!
while (m != 0) {
System.out.println(m);
m += m * 12381923;
counter++;
}
System.out.println(m);
System.out.println("Converged after " + counter + " iterations.");
}
}
Hope this helps!
It is because the int value overflows. The following documentation shows that the maximum value of an int is 2,147,483,647 and by the time the sixteenth iteration occurs, m is greater than this value and hence it overflows.
Is there a difference between ++x and x++ in java?
++x is called preincrement while x++ is called postincrement.
int x = 5, y = 5;
System.out.println(++x); // outputs 6
System.out.println(x); // outputs 6
System.out.println(y++); // outputs 5
System.out.println(y); // outputs 6
yes
++x increments the value of x and then returns x
x++ returns the value of x and then increments
example:
x=0;
a=++x;
b=x++;
after the code is run both a and b will be 1 but x will be 2.
These are known as postfix and prefix operators. Both will add 1 to the variable but there is a difference in the result of the statement.
int x = 0;
int y = 0;
y = ++x; // result: x=1, y=1
int x = 0;
int y = 0;
y = x++; // result: x=1, y=0
Yes,
int x=5;
System.out.println(++x);
will print 6 and
int x=5;
System.out.println(x++);
will print 5.
In Java there is a difference between x++ and ++x
++x is a prefix form:
It increments the variables expression then uses the new value in the expression.
For example if used in code:
int x = 3;
int y = ++x;
//Using ++x in the above is a two step operation.
//The first operation is to increment x, so x = 1 + 3 = 4
//The second operation is y = x so y = 4
System.out.println(y); //It will print out '4'
System.out.println(x); //It will print out '4'
x++ is a postfix form:
The variables value is first used in the expression and then it is incremented after the operation.
For example if used in code:
int x = 3;
int y = x++;
//Using x++ in the above is a two step operation.
//The first operation is y = x so y = 3
//The second operation is to increment x, so x = 1 + 3 = 4
System.out.println(y); //It will print out '3'
System.out.println(x); //It will print out '4'
Hope this is clear. Running and playing with the above code should help your understanding.
I landed here from one of its recent dup's, and though this question is more than answered, I couldn't help decompiling the code and adding "yet another answer" :-)
To be accurate (and probably, a bit pedantic),
int y = 2;
y = y++;
is compiled into:
int y = 2;
int tmp = y;
y = y+1;
y = tmp;
If you javac this Y.java class:
public class Y {
public static void main(String []args) {
int y = 2;
y = y++;
}
}
and javap -c Y, you get the following jvm code (I have allowed me to comment the main method with the help of the Java Virtual Machine Specification):
public class Y extends java.lang.Object{
public Y();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_2 // Push int constant `2` onto the operand stack.
1: istore_1 // Pop the value on top of the operand stack (`2`) and set the
// value of the local variable at index `1` (`y`) to this value.
2: iload_1 // Push the value (`2`) of the local variable at index `1` (`y`)
// onto the operand stack
3: iinc 1, 1 // Sign-extend the constant value `1` to an int, and increment
// by this amount the local variable at index `1` (`y`)
6: istore_1 // Pop the value on top of the operand stack (`2`) and set the
// value of the local variable at index `1` (`y`) to this value.
7: return
}
Thus, we finally have:
0,1: y=2
2: tmp=y
3: y=y+1
6: y=tmp
When considering what the computer actually does...
++x: load x from memory, increment, use, store back to memory.
x++: load x from memory, use, increment, store back to memory.
Consider:
a = 0
x = f(a++)
y = f(++a)
where function f(p) returns p + 1
x will be 1 (or 2)
y will be 2 (or 1)
And therein lies the problem. Did the author of the compiler pass the parameter after retrieval, after use, or after storage.
Generally, just use x = x + 1. It's way simpler.
Yes.
public class IncrementTest extends TestCase {
public void testPreIncrement() throws Exception {
int i = 0;
int j = i++;
assertEquals(0, j);
assertEquals(1, i);
}
public void testPostIncrement() throws Exception {
int i = 0;
int j = ++i;
assertEquals(1, j);
assertEquals(1, i);
}
}
Yes, using ++X, X+1 will be used in the expression. Using X++, X will be used in the expression and X will only be increased after the expression has been evaluated.
So if X = 9, using ++X, the value 10 will be used, else, the value 9.
If it's like many other languages you may want to have a simple try:
i = 0;
if (0 == i++) // if true, increment happened after equality check
if (2 == ++i) // if true, increment happened before equality check
If the above doesn't happen like that, they may be equivalent
Yes, the value returned is the value after and before the incrementation, respectively.
class Foo {
public static void main(String args[]) {
int x = 1;
int a = x++;
System.out.println("a is now " + a);
x = 1;
a = ++x;
System.out.println("a is now " + a);
}
}
$ java Foo
a is now 1
a is now 2
OK, I landed here because I recently came across the same issue when checking the classic stack implementation. Just a reminder that this is used in the array based implementation of Stack, which is a bit faster than the linked-list one.
Code below, check the push and pop func.
public class FixedCapacityStackOfStrings
{
private String[] s;
private int N=0;
public FixedCapacityStackOfStrings(int capacity)
{ s = new String[capacity];}
public boolean isEmpty()
{ return N == 0;}
public void push(String item)
{ s[N++] = item; }
public String pop()
{
String item = s[--N];
s[N] = null;
return item;
}
}
Yes, there is a difference, incase of x++(postincrement), value of x will be used in the expression and x will be incremented by 1 after the expression has been evaluated, on the other hand ++x(preincrement), x+1 will be used in the expression.
Take an example:
public static void main(String args[])
{
int i , j , k = 0;
j = k++; // Value of j is 0
i = ++j; // Value of i becomes 1
k = i++; // Value of k is 1
System.out.println(k);
}
The Question is already answered, but allow me to add from my side too.
First of all ++ means increment by one and -- means decrement by one.
Now x++ means Increment x after this line and ++x means Increment x before this line.
Check this Example
class Example {
public static void main (String args[]) {
int x=17,a,b;
a=x++;
b=++x;
System.out.println(“x=” + x +“a=” +a);
System.out.println(“x=” + x + “b=” +b);
a = x--;
b = --x;
System.out.println(“x=” + x + “a=” +a);
System.out.println(“x=” + x + “b=” +b);
}
}
It will give the following output:
x=19 a=17
x=19 b=19
x=18 a=19
x=17 b=17
public static void main(String[] args) {
int a = 1;
int b = a++; // this means b = whatever value a has but, I want to
increment a by 1
System.out.println("a is --> " + a); //2
System.out.println("b is --> " + b); //1
a = 1;
b = ++a; // this means b = a+1
System.out.println("now a is still --> " + a); //2
System.out.println("but b is --> " + b); //2
}
With i++, it's called postincrement, and the value is used in whatever context then incremented; ++i is preincrement increments the value first and then uses it in context.
If you're not using it in any context, it doesn't matter what you use, but postincrement is used by convention.
There is a huge difference.
As most of the answers have already pointed out the theory, I would like to point out an easy example:
int x = 1;
//would print 1 as first statement will x = x and then x will increase
int x = x++;
System.out.println(x);
Now let's see ++x:
int x = 1;
//would print 2 as first statement will increment x and then x will be stored
int x = ++x;
System.out.println(x);
Try to look at it this way:
from left to right do what you encounter first. If you see the x first, then that value is going to be used in evaluating the currently processing expression, if you see the increment (++) first, then add one to the current value of the variable and continue with the evaluation of the expression. Simple