The following small programs which compute the sum of all numbers from 1 to 1 billion we're written in C++ and Java as closely as I could write them. My understanding is that C++ is the "faster" language, but the java version of this code completes in ~.5 seconds vs ~3 seconds for C++.
C++ (GCC Compiler):
int main(){
long long x = 0;
for (long i=0;i<1000000001;i++){
x=x+i;
}
cout << x << endl;
return 0;
}
JAVA:
public class Main {
public static void main(String[] args) {
long x=0;
for (long i=0;i<1000000001;i++){
x=x+i;
}
System.out.println(x);
}
}
How would one optimize the C++ code to be as fast as the JAVA version? Is it even possible?