Search code examples
timestacklimit

How can i do that counting limits take too much time for big integers?


Im Vladimir Grygov and I have very serious problem.

In our work we now work on really hard algorithm, which using limits to cout the specific result.

Alghoritm is veary heavy and after two months of work we found really serious problem. Our team of analytics told me to solve this problem.

For the first I tell you the problem, which must be solve by limits: We have veary much datas in the database. Ec INT_MAX. For each this data we must sort them by the alghoritm to two groups and one must have red color interpretation and second must be blue.

The algorithm counts with ID field, which is some AUTO_INCREMENT value. For this value we check, if this value is eequal to 1. If yeas, this is red color data. If it is zero, this is blue data. If it is more. Then one, you must substract number 2 and check again.

We choose after big brainstorming method by for loop, but this was really slow for bigger number. So we wanted to remove cycle, and my colegue told me use recursion.

I did so. But... after implementation I had got unknown error for big integers and for example long long int and after him was wrote that: "Stack Overflow Exception"

From this I decided to write here, because IDE told me name of this page, so I think that here may be Answer.

Thank You so much. All of you.


Solution

  • After your comment I think I can solve it:

    public bool isRed(long long val) { 
    if (val==1) 
      {return true; } 
    else if (val==0) 
      { return false; } 
      else { return isRed(val - 2); }
    }
    

    Any halfway decent value for val will easily break this. There is just no way this could have worked with recursion. No CPU will support a stacktrace close to half long.MaxInt!

    However there are some general issues with your code:

    1. Right now this is the most needlesly complex "is the number even" check ever. Most people use Modulo to figure that out. if(val%2 == 0) return false; else return true;
    2. the type long long seems off. Did you repeat the type? Did you mean to use BigInteger?
    3. If the value you substract by is not static and it is not solveable via modulo, then there is no reason not to use a loop here.

      public bool isRed (long long val){ for(;val >= 0; val = val -2){ if(value == 0) return false; } return true; }