Calculating the Collatz Conjecture Today I read this thing about the Collatz Conjecture and wanted to try and write a program that calculates all the numbers. If you have any idea how the code could be shortened, please tell me.

List&lt;string&gt; liste = new List&lt;string&gt;();
long num = 1;
        long z = num;

        while (num != 100000)
        {
            while (z != 1)
            {
                if (z % 2 == 0)
                {
                    z = z / 2;
                }
                else
                {
                    z = (z * 3) + 1;
                }
            }
            liste.Add(num + ": " + z);
            Console.WriteLine(num+": "+z);
            finalnumber = z;
            num++;
        }

            string path = @"N:\Desktop\test.txt";
            File.Delete(path);
            for (int i = 0; i &lt; liste.Count; i++)
            {
                string appendText = ""+liste[i]+"" + Environment.NewLine;
                File.AppendAllText(path, appendText);
            }
Each time you call File.AppendAllText, you create a new files stream and close it afterwards. Therfore, you should not write the result into the file by calling File.AppendAllText n times. just use string.Join instead:

var content = string.Join(Environment.NewLine, list);
File.WriteAllText(content);




Your code seems not work correctly, because if z == 1 is reached (which is given as initial state), the inner while loop is not entered anymore. I suppose there is a z = num; missing at the end of the outer while loop.



And in the very unlikely event, that you find a start number where the collatz conjecture does not ends up with 1, your program remains in an endless loop and you will never find out which number it was ;).