A coin counting algorithm