Implement factorial recursively

Source: Internet
Author: User

If you want to implement a factorial, such as 6*5*4*3*2*1, you may first think of loop traversal. As follows:

    class Program
    {
        static void Main(string[] args)
        {
Console. writeline ("enter a number ");
            int number = Convert.ToInt32(Console.ReadLine());
            double result = JieCheng(number);
The factorial result of console. writeline (number. tostring () + "is:" + result. tostring ());
            Console.ReadKey();
        }
 
        public static double JieCheng(int number)
        {
            if (number == 0)
            {
                return 0;
            }
 
// The initial value must be set to 1.
            double result = 1;
 
            for (int i = number; i >= 1; i--)
            {
                result = result*i;
            }
            return result;
        }
    }

However, there is another way to implement the factorial: 6 * (6-1) * (6-2) * (6-3) * (6-4) * (6-5) or 6 * (6-1) * (5-1) * (4-1) * (3-1) * (2-1 ), that is to say, the following number is always obtained by subtracting 1 from the previous number.

 

When the implementation logic is the same, and the parameters of the internal recursive method can be obtained by the parameters of the external recursive method through a certain algorithm, this is exactly the time when recursion came into being.

        public static double JieCheng(int number)        {            if (number == 0)            {                return 1;            }            return number * JieCheng(number - 1);        }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.