Calculates Ulam's algorithm