C# program to generate Collatz Conjecture sequence.

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

// © 2017 TheFlyingKeyboard and released under MIT License
// theflyingkeyboard.net

namespace CollatzConjecture
{
    class Program
    {
        static void Main(string[] args)
        {
            int number;
            int iterNum = 0;

            Console.Write("Enter a number: ");
            number = Convert.ToInt32(Console.ReadLine());

            if (number > 0)
            {
                Console.Write("{0} ", number);

                while(number != 1)
                {
                    number = collatzConjecture(number);
                    Console.Write(" {0}", number);

                    iterNum++;
                }

                Console.WriteLine("");
                Console.WriteLine("It took {0} iterations to reach 1", iterNum);
            }

            Console.ReadKey();
        }

        static int collatzConjecture(int num)
        {
            if (num % 2 == 0)
            {
                return num / 2;
            }
            else
            {
                return 3 * num + 1;
            }
        }
    }
}

 

C# Collatz Conjecture Sequence Generator
Tagged on:     

Leave a Reply

Your email address will not be published. Required fields are marked *

This website stores some user agent data. These data are used to provide a more personalized experience and to track your whereabouts around our website in compliance with the European General Data Protection Regulation. If you decide to opt-out of any future tracking, a cookie will be set up in your browser to remember this choice for one year. I Agree, Deny
504