Java Recursive Algorithm

Source: Internet
Author: User

Java Recursive Algorithm

Recursive Algorithms are actually called by the program itself. When performing a recursive algorithm, you must have a clear recursion termination condition,
When this condition is met, recursion is no longer performed.


The following two basic recursive algorithms are implemented using Java:

/*** Calculate 1 + 2 + 3 +... + n and */class Recurrent {int sum = 0; int flag = 1; public void count (int number) {sum + = flag; flag ++; if (flag <= number) {count (number) ;}} public class T {public static void main (String [] args) {Recurrent r = new Recurrent (); r. count (5); System. out. println (r. sum );}}
/*** Calculate the Factorial of n */class Factorial {public long mul (int n) {if (n <= 1) {return 1 ;} else {return n * mul (n-1) ;}} public class T {public static void main (String [] args) {Factorial fac = new Factorial (); System. out. println (fac. mul (15 ));}}

 

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.