"Disease Spread" challenge Right now I'm solving this problem on codewars.com. I'm not sure about how to optimise the code further. Or is my algorithm inefficient? If it's an algorithmic issue, could someone help me how to go about it?

import java.util.Arrays;

class Epidem {

    public static int epidemic(int tm, int n, int s0, int i0, double b, double a) {
        // your code
     double dt = tm/n;
     double s1,i1,r,j;
     r=0;j=0;

     while(j&lt;=tm)
      {
      s1 = s0 - dt*b*s0*i0;
      i1 = i0 + dt*(b*s0*i0 - a*i0);
      r = r + dt * i0 * a;
      s0 = (int) s1;
      i0 = (int) i1;
      j+=dt;
      }

     return (int) i0;

    }
}


It fails in the following cases:

int tm = 18 ;int n = 432 ;int s0 = 1004 ;int i0 = 1 ;double b = 0.00209 ;double a = 0.51;

    tm = 12 ;n = 288 ;s0 = 1007 ;i0 = 2 ;b = 0.00206 ;a = 0.45;

    tm = 13 ;n = 312 ;s0 = 999 ;i0 = 1 ;b = 0.00221 ;a = 0.55;

    tm = 24 ;n = 576 ;s0 = 1005 ;i0 = 1 ;b = 0.00216 ;a = 0.45;

    tm = 24 ;n = 576 ;s0 = 982 ;i0 = 1 ;b = 0.00214 ;a = 0.44;

    tm = 20 ;n = 480 ;s0 = 1000 ;i0 = 1 ;b = 0.00199 ;a = 0.53;

    tm = 28 ;n = 672 ;s0 = 980 ;i0 = 1 ;b = 0.00198 ;a = 0.44;

    tm = 14 ;n = 336 ;s0 = 996 ;i0 = 2 ;b = 0.00206 ;a = 0.41;

    tm = 13 ;n = 312 ;s0 = 993 ;i0 = 2 ;b = 0.0021 ;a = 0.51;

    tm = 28 ;n = 672 ;s0 = 999 ;i0 = 1 ;b = 0.00197 ;a = 0.55;
Already answered by @Thomasky:

double dt = ((double)tm) / n;


There are some common subexpressions, multiplications, you need to do only once. like b*(s0*i0) (integer multiplication first).

The while loop would better go as (more precise, faster):

for (int j = 0; j &lt; n; ++j) {
    double bsi = dt*b*(s0*i0);
    double ai = dt*a*i0
    s0 -= (int) -bsi;
    i0 += (int) (bsi - ai);
    //r += ai; // As unused?
}


Variables can (and should) be declared as locally as possible, a declaration in a loop does not do more work as outside; there is just one slot reserved on the function stack.

The cast of (int) does no rounding.
As you might imagine, n*dt increases the approximation error in dt by n-fold. However more precision, a correction, would cost time.

Maybe using doubles, say double s1 = s0; double i1 = i0; instead of s0 and i0 would give a better solution. No idea.

And finally this task is solvable with a bit of math.