Recursive Algorithms for bottle problems. (Reminds me of BaO Qian a while ago -_-!)

Source: Internet
Author: User

Forum address: http://topic.csdn.net/u/20081214/00/5285a066-d37b-455f-a3be-4bb15aeda0ef.html? Seed = 290962744

 

The scenario is: one yuan a bottle of soda, two empty bottles can change one bottle of soda.
If you have X yuan, you can drink y bottles of soda, which is represented by Y = f (x ).

If n empty bottles are used for another empty bottle, y = f (x, n) indicates

 

My code, if it is 2 for 1:

 

  1. Package lihan;
  2. Public class test {
  3. Public static integer digui (int x)
  4. {
  5. If (x = 1)
  6. {
  7. Return X;
  8. }
  9. If (X % 2 = 1)
  10. Return x + digui (X/2) + 1;
  11. Else
  12. Return x + digui (X/2 );
  13. }
  14. /**
  15. * @ Param ARGs
  16. */
  17. Public static void main (string [] ARGs ){
  18. // Todo automatically generates method stubs
  19. Int I = digui (11 );
  20. System. Out. Print (I );
  21. }
  22. }

If n is used for 1, then

 

  1. Public class lihan {
  2. Public static integer digui (int x, int N)
  3. {
  4. If (x = 1)
  5. {
  6. Return X;
  7. }
  8. If (X % N = (n-1 ))
  9. Return x + digui (x/n, n) + 1;
  10. Else
  11. Return x + digui (x/N, N );
  12. }
  13. /**
  14. * @ Param ARGs
  15. */
  16. Public static void main (string [] ARGs ){
  17. // Todo automatically generates method stubs
  18. Int I = digui (12, 3) + 1;
  19. System. Out. Print (I );
  20. }
  21. }

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.