Simple data collation, recursive algorithm

Source: Internet
Author: User

Today touched a bit of recursion, the beginning of the time do not know what the meaning, just follow the answer code copied down, you can achieve their own purposes, on the Internet to see the feeling is not difficult to understand

But honestly, if you want to use it well, it's not a simple thing.

First look at a piece of code to find the factorial of a number

 Public classQQQ {//calculates the factorial of a number    Private Static intFactinta) {//the factorial of 1 would have been 1, and it would return directly .        if(a==1) {            returnA; }        Else {            return(A * fact (A-1)); }    }     Public Static voidMain (string[] args) {System.out.println (Fact (6)); }}

Recursion to a large extent similar to the loop, but not the loop, recursion is there to go back, the loop is to go back, in many cases recursion can be the code is simpler, but also easier to understand (this is really not found ...),

Look at this picture again.

This is the process diagram for calculating the factorial of a number using a recursive algorithm.

Principle is

Factorial ==6 of 6 times the factorial of 5

Factorial ==5 of 5 times the factorial of 4

Factorial ==4 of 4 times the factorial of 3

Factorial ==3 of 3 times the factorial of 2

Factorial ==2 of 2 times the factorial of 1

Factorial ==1 of 1

And then there's this thing in turn:

The factorial ==6 of 6 times 5 times 4 times 3 times 2 times 1 ...

So the factorial of 6 comes out.

Simple data collation, recursive algorithm

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.