码迷,mamicode.com
首页 > 其他好文 > 详细

Factorial

时间:2015-07-02 09:54:35      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:

Factorial  计算阶乘

In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example: 5! = 5 * 4 * 3 * 2 * 1 = 120. By convention the value of 0! is 1.

Write a function to calculate factorial for a given input. If input is below 0 or above 12 throw an exception of type ArgumentOutOfRangeException (C#) or IllegalArgumentException (Java).

More details about factorial can be found here: http://en.wikipedia.org/wiki/Factorial

刚开始没有注意题目的提示,可以直接判断大于12,就溢出了。想到了使用checked关键字来检查是否溢出。

https://msdn.microsoft.com/zh-cn/library/74b4xzyw.aspx   checked关键字的用法

public static class Kata
    {
        public static int Factorial(int n)
        {
            try
            {
                return Recursion(n);
            }
            catch
            {
                throw;
            }
        }

        public static int Recursion(int n)
        {
            if (n < 0)
            {
                throw new ArgumentOutOfRangeException();
            }
            try
            {

                int factorial = 1;
                if (n >= 2)
                {
                    checked
                    {
                        factorial = n * Recursion(n - 1);
                    }
                }
                return factorial;
            }
            catch
            {
                throw new ArgumentOutOfRangeException();
            }
        }
    }

 

其他人的解法:

public static int Factorial(int n)
  {
    if(n < 0 || n > 12)
      throw new ArgumentOutOfRangeException();    
    return n > 0 ? n * Factorial(n - 1) : 1;
  }

 

 

using System;
using System.Linq;

public static class Kata
{
  public static int Factorial(int n)
  {
    if(n < 0 || n > 12) throw new ArgumentOutOfRangeException();
    
    return Enumerable.Range(1, n).Aggregate(1, (x,y) => x * y);
  }
}

 

Factorial

标签:

原文地址:http://www.cnblogs.com/chucklu/p/4615157.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!