用本地函数和模式表达式实现斐波拉齐和阶乘

新的C#增加了一些好用的特性,本地函数提升了递归的性能,模式匹配阅读性更好,今天来试用一下,先写个斐波那齐方法。

 public static ulong[] GetFibonacciArray(ulong index)
        {
            ulong[] fibonacciArray = default;
            if (index < 1)
            {
                throw new ArgumentOutOfRangeException(nameof(index));
            }
            else
            {
                fibonacciArray = new ulong[index];
            }

            for (ulong i = 0; i < index; i++)
            {
                fibonacciArray[i] = LocalFibonacci(i);
            }

            return fibonacciArray;

            static ulong LocalFibonacci(ulong index) => index switch
            {
                < 1 => 0,
                1 => 1,
                _ => LocalFibonacci(index - 1) + LocalFibonacci(index - 2)
            };
        }

再写个阶乘的方法

public static ulong Factorial(ulong x)
        {
            return LocalFactorial(x);

            static ulong LocalFactorial(ulong x) => x switch
            {
                < 1 or 1 => 1,
                _ => x * LocalFactorial(x - 1)
            };
        }

运行看看

using FibonacciAndFactorial;
Console.WriteLine("获取斐波拉齐数组");
foreach(var i in SimpleLibrary.GetFibonacciArray(28))
{
    Console.Write(i);
    Console.Write(" ");
}

Console.WriteLine();
Console.WriteLine("演示阶乘");
for (int i = 0; i < 11; i++)
{
    Console.WriteLine($"{i,3}!={SimpleLibrary.Factorial(Convert.ToUInt64(i))}");
}
Console.WriteLine();

 写代码时感觉很爽,以后就用它了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值