The following sequence has to be printed.
12345 2345 345 45 5
This can be done using one loops or two loops, but surprisingly when I use two loops, it takes a lot more time.
Here is what I have done. One loop way:
//Prints are commented so that outputs are easily visible
public void generateSequence1(int num){
long timeStarted = System.currentTimeMillis();
for(int j = 1, i= 1; i<=num && j<= num; ){
i++;
// System.out.print(i++);
if(i==num+1){
i = ++j;
// System.out.println();
}
}
System.out.println("Using 1 loop, time taken: " + (System.currentTimeMillis() - timeStarted));
}
Here is the Two loop way
public void generateSequencePlainWay(int num){
long timeStarted = System.currentTimeMillis();
for(int i = 1; i<= num; i++){
for(int j = i;j <= num; j++){
// System.out.print(j);
}
// System.out.println();
}
System.out.println("Using 2 loop, time taken: " + (System.currentTimeMillis() - timeStarted));
}
Now when I call the methods
TestConducts tc = new TestConducts();
tc.generateSequencePlainWay(50000);
tc.generateSequence1(50000);
The output is as follows.(I fluctuates a bit each time, but almost the same)
Using 2 loop, time taken: 668
Using 1 loop, time taken: 7
Both these methods have n*(n-1)/2 operations. Then why such a huge time difference? Am I doing something wrong? Or this is the way it should be?And which way is better?