Search code examples
c#recursioninteger-division

Terras Conjecture in C#


I'm having a problem generating the Terras number sequence.

Terras formula

Here is my unsuccessful attempt:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Terras
{
    class Program
    {
        public static int Terras(int n)
        {
            if (n <= 1)
            {
                int return_value = 1;
                Console.WriteLine("Terras generated : " + return_value);

                return return_value;
            }
            else
            {
                if ((n % 2) == 0)
                {
                    // Even number
                    int return_value = 1 / 2 * Terras(n - 1);
                    Console.WriteLine("Terras generated : " + return_value);

                    return return_value;
                }
                else
                {
                    // Odd number
                    int return_value = 1 / 2 * (3 * Terras(n - 1) + 1);
                    Console.WriteLine("Terras generated : " + return_value);

                    return return_value;
                }
            }
        }
        static void Main(string[] args)
        {
            Console.WriteLine("TERRAS1");
            Terras(1); // should generate 1

            Console.WriteLine("TERRAS2");
            Terras(2); // should generate 2 1 ... instead of 1 and 0

            Console.WriteLine("TERRAS5");
            Terras(5); // should generate 5,8,4,2,1 not 1 0 0 0 0

            Console.Read();
        }
    }
}

What am I doing wrong?

I know the basics of recursion, but I don’t understand why this doesn’t work.

I observe that the first number of the sequence is actually the number that you pass in, and subsequent numbers are zero.


Solution

  • Change 1 / 2 * Terros(n - 1); to Terros(n - 1)/2;

    Also 1 / 2 * (3 * Terros(n - 1) + 1); to (3 * Terros(n - 1) + 1)/2;

    1/2 * ... is simply 0 * ... with int math.


    [Edit]

    Recursion is wrong and formula is mis-guided. Simple iterate

    public static void Terros(int n) {
      Console.Write("Terros generated :");
      int t = n;
      Console.Write(" " + t);
      while (t > 1) {
        int t_previous = t;
        if (t_previous%2 == 0) {
          t = t_previous/2;
        }
        else {
          t = (3*t_previous+1)/2;
        }
        Console.Write(", " + t);
      }
      Console.WriteLine("");
    }
    

    The "n is even" should be "t(subscript n-1) is even" - same for "n is odd".