1. 程式人生 > >C#寫水仙花數--用到遞迴

C#寫水仙花數--用到遞迴

</pre><pre name="code" class="csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NarcissisticNumber
{
    class NarNumber//建立水仙數的類,在Main中呼叫此類
    {
        public void NarcisNumber()
        {
            Console.WriteLine("*****************輸出100~999的水仙花數***************");
            Console .Write("\n\t100~999之間的水仙花數為:");

            for (int i = 100; i <= 999; i++)
            {
                if (judge(i))
                {
                    Console.Write("{0} ",i);
                }
            }
            Console.WriteLine("\n\n****************************************************\n\n");
        }

        public void Narcinumber()//判斷四位數是否為水仙數的函式
        {
            Console.WriteLine("*****************輸出1000~9999的水仙花數************");
            Console.Write("\n\t1000~9999的水仙花數為:");

            for (int i = 1000; i <= 9999; i++)
            {
                if (Judge(i))
                {
                    Console.Write("{0} ", i);
                }
            }
            Console.WriteLine("\n\n****************************************************\n\n");
        }

        public bool judge(int num)  //判斷三位水仙花數的語句
        {
            int a, b, c;
            a = num / 100;
            b = (num - a * 100) / 10;
            c = num % 10;

            if (num == Recurison(a,3) + Recurison(b,3) + Recurison(c,3))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public bool Judge(int num)      //判斷四位數為水仙數的語句
        {
            int a, b, c, d;
            a = num / 1000;
            b = num % 1000 / 100;
            c = num % 100 / 10;
            d = num % 10;

            if (num == Recurison(a,4) + Recurison(b,4) + Recurison(c,4) + Recurison(d,4))
            {
                return true;
            }
            else 
            {
                return false;
            }
        }

        public int Recurison(int num, int n)  //利用遞迴計算  a^4
        {
            if (n == 1)
            {
                return num;
            }
            else
            {
                return num * Recurison(num,n-1);
            }
        }

    }

    class Program
    {
        static void Main(string[] args)
        {
            NarNumber a = new NarNumber();//構造新的NarNumber函式
            //判斷三位數的呼叫的函式類
            a.NarcisNumber();
            //判斷四位數的呼叫的函式類
            a.Narcinumber();
            Console.ReadKey();//防止程式閃退
        }
    }
}
</pre><pre name="code" class="csharp">在其中用到遞迴計算次方,例如:a^3,對自己來說回顧了一下新的演算法!
</pre><pre name="code" class="csharp">首先建立了一個名為NarNumber的類,在主函式Main中通過 new 重新建構函式 NarNumber a = new NarNumber();
//構造新的NarNumber函式
並通過 a 來呼叫NarNumber中的類