1

The below given code is taking so much time to execute code correct answer

for(long i=0;i<9223372036854775807;i++){
   //code
}

Can anyone tell me any alternative approach or correction of this version?

3 Answers3

2

from this answer https://stackoverflow.com/a/15505663/7806805 and since your question is

The below given code is taking so much time to execute code correct answer

If you were executing your function once per nanosecond, it would still take over 292 years to encounter this situation according to this source.

so its natural for it to take time

Ishan Srivastava
  • 1,129
  • 1
  • 11
  • 29
2

The one change you could make is to use the constant Long.MAX_VALUE instead.

But don't expect that to change anything. That loop still takes all the time it takes to iterate that range.

In other words: how you express "I want to iterate 2 to the power of 63 minus 1" times doesn't influence the time required to do that at all.

The only thing to cut runtime is by slicing the range and have multiple smaller loops go in parallel. But of course: without any detail on the loop body it is not possible to determine whether parallelism is applicable here.

And of course, the real question would be about the actual problem that you intend to solve by iterating code for millions, billions of years.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
-1

I suggest to use Long.MAX_VALUE as a loop bound:

for(long i=0L;i<Long.MAX_VALUE;i++){
//code
  }
Mustapha Belmokhtar
  • 1,231
  • 8
  • 21