Factorial
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 < )
{
throw new ArgumentOutOfRangeException();
}
try
{ int factorial = ;
if (n >= )
{
checked
{
factorial = n * Recursion(n - );
}
}
return factorial;
}
catch
{
throw new ArgumentOutOfRangeException();
}
}
}
其他人的解法:
递归计算
public static int Factorial(int n)
{
if(n < || n > )
throw new ArgumentOutOfRangeException();
return n > ? n * Factorial(n - ) : ;
}
using System;
using System.Linq; public static class Kata
{
public static int Factorial(int n)
{
if(n < || n > ) throw new ArgumentOutOfRangeException(); return Enumerable.Range(, n).Aggregate(, (x,y) => x * y);
}
}
需要注意的是
public static TAccumulate Aggregate<TSource, TAccumulate>(
this IEnumerable<TSource> source,
TAccumulate seed,
Func<TAccumulate, TSource, TAccumulate> func
)
Type Parameters
- TSource
-
The type of the elements of source. 源数据中的数据的类型
- TAccumulate
-
The type of the accumulator value. 累加器的值的类型
Parameters
- source
- Type: System.Collections.Generic.IEnumerable<TSource>
An IEnumerable<T> to aggregate over. //源数据
- seed
- Type: TAccumulate
The initial accumulator value. 累加器的初始值
- func
- Type: System.Func<TAccumulate, TSource, TAccumulate>
An accumulator function to be invoked on each element. 每一个元素调用的累加器函数
Return Value
Type: TAccumulate
The final accumulator value. 返回值是累加器的最终值
https://msdn.microsoft.com/zh-cn/library/bb549218(v=vs.110).aspx
The Aggregate<TSource, TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate, TSource, TAccumulate>) method
makes it simple to perform a calculation over a sequence of values.
此方法使得在一个序列上进行计算变得简单
This method works by calling func one time for each element in source.
此方法的通过让序列中的每个元素都会调用一次func委托来工作。
Each time func is called, Aggregate<TSource, TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate, TSource, TAccumulate>) passes both the element from the sequence and an aggregated value (as the first argument to func).
每一次调用委托的时候,此方法传递序列中的当前元素以及累加值(累加值是作为fun中的第一个参数的)
The value of the seed parameter is used as the initial aggregate value.
seed参数作为累计值的初始值
The result of func replaces the previous aggregated value. Aggregate<TSource, TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate, TSource, TAccumulate>) returns the final result of func.
func委托的返回值,会替代之前的累计值。 此方法返回func委托的最终结果
To simplify common aggregation operations, the standard query operators also include a general purpose count method, Count, and four numeric aggregation methods, namely Min, Max, Sum, and Average.
为了简化通用的聚合操作,标准查询操作符也包含了一个通过计数方法Count,此外,还有4个数值聚合方法,名为Min,Max,Sum和Average。
最后分析一下
Enumerable.Range(1, n).Aggregate(1, (x,y) => x * y)
Enumerable.Range(1, n)通过这个获取1到n的序列
Aggregate(1, (x,y) => x * y)其中1作为累加值的初始值 lambda表达式中的第一个参数表示的就是累加值,然后将x*y的值替换掉累加值,并作为下一次调用的x传入
遍历1到n
1 x=1,y=1 x=1*1;
2 x=1,y=2 x= 1*2;
3 x=2,y=3 x= 2*3
特别需要注意的是,当n=0的时候;Enumerable.Range(1, 0)中一个元素也没有,直接返回了累加器的初始值1
Factorial的更多相关文章
- [LeetCode] Factorial Trailing Zeroes 求阶乘末尾零的个数
Given an integer n, return the number of trailing zeroes in n!. Note: Your solution should be in log ...
- CodeForces 515C. Drazil and Factorial
C. Drazil and Factorial time limit per test 2 seconds memory limit per test 256 megabytes input stan ...
- [CareerCup] 17.3 Factorial Trailing Zeros 求阶乘末尾零的个数
LeetCode上的原题,讲解请参见我之前的博客Factorial Trailing Zeroes. 解法一: int trailing_zeros(int n) { ; while (n) { re ...
- [codeforces 516]A. Drazil and Factorial
[codeforces 516]A. Drazil and Factorial 试题描述 Drazil is playing a math game with Varda. Let's define ...
- LeetCode Factorial Trailing Zeroes
原题链接在这里:https://leetcode.com/problems/factorial-trailing-zeroes/ 求factorial后结尾有多少个0,就是求有多少个2和5的配对. 但 ...
- 【LeetCode】172. Factorial Trailing Zeroes
Factorial Trailing Zeroes Given an integer n, return the number of trailing zeroes in n!. Note: Your ...
- SPOJ #11 Factorial
Counting trailing 0s of n! It is not very hard to figure out how to count it - simply count how many ...
- 欧拉工程第74题:Digit factorial chains
题目链接:https://projecteuler.net/problem=74 数字145有一个著名的性质:其所有位上数字的阶乘和等于它本身. 1! + 4! + 5! = 1 + 24 + 120 ...
- CF Drazil and Factorial (打表)
Drazil and Factorial time limit per test 2 seconds memory limit per test 256 megabytes input standar ...
随机推荐
- linux系统时间修改及同步
时间修改date 月日时分年.秒date -s可以直接设置系统时间 比如将系统时间设定成1996年6月10日的命令如下.#date -s 06/10/96将系统时间设定成下午1点12分0秒的命令如下. ...
- NoSQL性能测试:MongoDB VS SequoiaDB
作 为NoSQL的一个重要类型,文档型NoSQL通常被认为是最接近传统关系型数据库的NoSQL.文档型NoSQL的核心是数据嵌套,这种设计可以从某种 程度上大大简化传统数据库复杂的关联问题.同时由于摆 ...
- 前端构建工具gulp入门教程
本文假设你之前没有用过任何任务脚本(task runner)和命令行工具,一步步教你上手Gulp.不要怕,它其实很简单,我会分为五步向你介绍gulp并帮助你完成一些惊人的事情.那就直接开始吧. 第一步 ...
- Kakfa揭秘 Day2 Kafka内核再揭秘
Spark Streaming揭秘 Day33 Kafka内核再揭秘 优秀的框架会把引擎做到极致,Kafka就是这样,让我们再深入一下研究. 设计目标 kafka系统有着比较独特的的设计,包括5点: ...
- zhuan:windows用一键安装包安装(推荐)-禅道
访问地址:http://www.zentao.net/book/zentaopmshelp/76.html 一键安装包 解压缩必须 解压缩到根目录下面.
- 《WPF程序设计指南》读书笔记——第1章 应用程序与窗口
1.空白WPF项目的创建: 1)新建项目:在VS2010中,文件-新建-项目-visual c#-windows-空项目: 2)添加引用:PresentationFramework,Presentat ...
- 【转】perl ping检测功能脚本代码
我的第一个用于生产环境的perl脚本,虽然不是很优秀,但也迈出了扎实的一步 :)领导有任务,给一批IP列表,ping每一台机器,如果没有响应就发邮件通知,通知的邮件需要分开,不能通知一个列表,得一封一 ...
- linux标准输入输出重定向
command > filename 把标准输出重定向到一个文件,如果文件不存在则新建,如果存在则覆盖其内容.command >> filename 把标准输出重定向到一个文件中,如 ...
- 彻底卸载网易UU网游加速器的方法
昨天跟朋友一起玩游戏,网速感觉不怎么好就下了一个免费的网易UU加速器来给对战平台加速,结果加速了以后网速更差,我晕,于是想卸载,可这个加速器口只有一个exe文件,不用安装,但在第一次加速时记得安装了一 ...
- multimap和multiset 认知和使用
之前只是在C++ Primer里面看过关联容器,可能因为没有实际用过,只是看看,所以导致用的时候并不熟悉: 在这之前,map和set的特性应该要了解,map是关联数组,也就是由键值对组成的,而set只 ...