public class DifferenceEngine { public static int f(int x, int[] coefficients) { int sum = 0; for (int i = 0; i < coefficients.length; i++) { int p = coefficients.length - i - 1; sum += coefficients[i] * Math.pow(x, p); } return sum; } public static void main(String[] args) { // f(x) = ax^n + bx^(n-1) ... // The coefficients a,b.. are listed here: int[] coefficients = { 1, 0, 4 }; // This example is x^2 + 0 x + 4 // n is the largest power (x^2 in this example) int n = coefficients.length - 1; int x = 3; int max_x = 6; // Initialize the differences int[] diffs = new int[n + 1]; for (int i = 0; i < n + 1; i++) { int x0 = x - n + i; int fx = f(x0, coefficients); int diff = fx - diffs[0]; diffs[0] = fx; for (int j = 1; j <= i; j++) { int d2 = diff - diffs[j]; diffs[j] = diff; diff = d2; } } // Actual Difference Engine Simulation // (you don't have to simulate the above part) while (x < max_x) { int i = diffs.length - 1; while (i > 0) { int d = diffs[i]; i -= 1; diffs[i] += d; } x++; System.out.println(x + " " + diffs[0]); } } }