P166: Sped up Java solution using algebra.