Just do it in two cases. Where a < b and where b < a. [java] import java.io.PrintWriter; import java.util.Scanner; /** * * @author Sanchit M. Bhatnagar * @see http://uhunt.felix-halim.net/id/74004 * */ public class P12468 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); while (sc.hasNextInt()) { int a = sc.nextInt(); int b = sc.nextInt(); if (a == -1) break; if (b < a) { out.println(Math.min(a - b, 100 - a + b)); } else { out.println(Math.min(b - a, 100 - b + a)); } out.flush(); } out.close(); sc.close(); } } [/java]