Lapping data structures and algorithms-Application of 06 recursion

Source: Internet
Author: User

One, simple demo

public class Recursion {

public static void Main (string[] args) {

Test (100);

}

public static void Test (int n) {

if (n = = 0) {

Return

}

SYSTEM.OUT.PRINTLN (n);

Test2 (n-1);

}

}

Two, triangle number


public class Triangle {

public static int GetNumber (int n) {

int total= 0;

while (n > 0) {

Total = Total + N;

n--;

}

return total;

}

public static int getnumberbyrecursion (int n) {

if (n = = 1) {

return 1;

} else {

return n + getnumberbyrecursion (n-1);

}

}

}

Test:

public class Testtriangle {

public static void Main (string[] args) {

System.out.println (Triangle.getnumber (500));

System.out.println (Triangle.getnumberbyrecursion (500));

}

}

Three, Fibonacci sequence.

public class Fibonacci {

public static int GetNumber (int n) {

if (n = = 1) {

return 0;

} else if (n = = 2) {

return 1;

} else {

Return GetNumber (n-1) + getnumber (n-2);

}

}

}

Test:

public class Testfibonacci {

public static void Main (string[] args) {

System.out.println (Fibonacci.getnumber (5));

}

}


This article is from the "8159085" blog, please be sure to keep this source http://8169085.blog.51cto.com/8159085/1696501

Lapping data structures and algorithms-Application of 06 recursion

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.