Recursive exercises, recursion

Source: Internet
Author: User

Recursive exercises, recursion

Number Accumulation

Accumulate prime numbers

Sample Code:

# Include <iostream> int sum (int); int judge (int); int sumOfPlain (int); int main (int argc, char ** argv) {// printf ("% d \ n", sum (3); // printf ("% d \ n", judge (5 )); printf ("% d \ n", sumOfPlain (10); // 2 3 5 7 return 0;} int sum (int a) {if (a <= 0) {return 0;} else if (a = 1) {return 1;} else return a + sum (A-1);}/** determine whether it is a prime number, if yes, otherwise, 0 */int judge (int a) is returned. {// There are three methods: until the A-1 // verified is to a/2 but because there is not half of this situation, so we may wish to add one more Number of children // then there is the range of division to the beginning. If it is still not available, it will not be available. For (int I = 2; I <a/2 + 1; I ++) {if (a % I = 0) {return 0 ;}} return ;} int sumOfPlain (int a) {int afterJ = judge (a); if (a <= 1) {return 0;} else if (a = 2) {return 2 ;} else {return afterJ + sumOfPlain (A-1 );}}

Recursion:

Advantages of recursion: the simplest algorithms are provided for some problems: Tower of Hanoi, binary search, fast sorting, and Fibonacci series. Disadvantages: (if there is no proper exit) the computer's resources will soon be exhausted. recursive Programs are hard to understand and maintain. For windows, the screen will not respond, but for linux, the system will restart. The Linux kernel is written in this way. It is automatically restarted when there is no available space in its memory. Suddenly thought of a cell phone... Automatic Restart is because the memory is gone and the linux kernel is packaged... Many android viruses use a recursion to restart the mobile phone and install it.

Related Article

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.