An attempt to write algorithm in c#