nyoj_94 Cigarettes Recursive vs iteration

Source: Internet
Author: User

Title Address

Analysis:

The English question actually understands the meaning and the normal also all is similar, even if has several words not to know also to be harmless.

A total of n cigarettes, a day to draw K branch.
After each K-branch, you get one.
Group A data.
Enter the number of n K, the output of a total smoke.
Ideas:
Recursion, the number of successful recursion, is the amount of smoke.
+n output can be.

recursion is written by itself, and iteration is the solution to the optimal program.
#include <iostream>using namespace Std;int daybyday (int n,int k)//Calculate the number of extra cigarettes, or how many days you have smoked {if (n/k<1)// The current smoke is not enough to finish the day return 0; else return Daybyday (n-k+1,k) +1; } int main () {int a;int n,k;cin>>a;while (a--) {cin>>n>>k;//cout<<daybyday (n,k) +n<<endl ;  recursion//Iteration int Sum=n;while (n/k) {sum+=n/k;   Update sum the  original n plus the number of days n=n/k+n%k;//update n} cout<<sum<<endl; }return 0;}


Two times and space utilization comparison:

It can be seen that the iterations are improved in the efficiency of time and space utilization.



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

nyoj_94 Cigarettes Recursive vs iteration

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.