public static void main(String[] args) { long[] d = new long[11590]; d[0] = 1; for (int i = 1; i <= 11589; i++) { d = d[i-1] + (i % 7) + ((((d[i-1] ^ i) & 3) == 0) ? 1 : 0); } System.out.println(d[11589]); } simply do a memorization and use bitwise operation to do modulo