Algorithm by Samuel Gregory