The following are the snippets in four different languages. They all are intended to do the same. But I find weird behaviour of Java Code when executed. Can anyone explain what is actually happening?
// C - Code
#include <stdio.h>
int main() {
int HELL = ((int)(1e9));
for(int i=0;i<HELL;i++) {
for(int j=0;j<HELL;j++) {
int k = i + j;
k++;
}
}
return 0;
}
// C++ Code
#include <bits/stdc++.h>
using namespace std;
int main() {
int HELL = ((int)(1e9));
for(int i=0;i<HELL;i++) {
for(int j=0;j<HELL;j++) {
int k = i + j;
k++;
}
}
return 0;
}
// Java Code
class Main {
public static void main(String[] args) {
int HELL = ((int)(1e9));
for(int i=0;i<HELL;i++) {
for(int j=0;j<HELL;j++) {
int k = i + j;
k++;
}
}
}
}
# Python Code
def main():
HELL = 10**9
for i in range(HELL):
for j in range(HELL):
k = i + j
k += 1
main()
I started executing those snippets one by one. If the program is executing for more than 3 seconds, I used ctrl + c key combo to stop the program. Surprisingly, the Java Program executed in less than 1 second.
Since its time complexity is O(N^2), and N is very huge, I thought it would take eternity to execute. But it didn’t happen like that. Can anyone explain?
It means there is some implicit optimisation taking place when we use -03?
Then why aren’t Python and C codes exiting immediately?
Are we supposed to use any extra arguments to make it happen?
PS: I am curious to know the reason. Do not ignore if it isn’t useful