Q for a given n, how can you change it to 1 with a minimal number of steps

Source: Internet
Author: User

If n is an even number, divide it by 2,
If n is an odd number, it is added 1 or minus 1.
Q for a given n, how can you change it to 1 with a minimal number of steps.
For example:
N= 61
n--60
N/2 30
N/2 15
n++ 16
N/2 8
N/2 4
N/2 2
N/2 1

Algorithm design: The first thought is the recursive algorithm, but think about we can dynamically plan: set A (i) for the integer I with a minimum of steps into a solution of 1, set n=i+1 then we consider a (n), if n is even, then a (n) = A (N/2) +1; If it is odd, then a (n) = Min (A ((n+1)/2+2), A ((n-1)/2 +2)). Algorithm initialization: Obviously a (1) = 0;

classTest { Public Static voidMain (string[] args) {intK = 45; int[] A =New int[k + 1]; a[1] = 1; Char[] C =New Char[k + 1];        ChangeTo1 (A, k, c);  for(inti = 0; i < a.length; i++) {System.out.println (i+ "," + c[i] + "," +A[i]); }    }    Private Static voidChangeTo1 (int[] A,intKChar[] c) { for(inti = 2; i < a.length; i++) {            if(i% 2 = = 0) {//evenA[i] = A[i/2] + 1; C[i]= ' # '; } Else {                if((a[(i + 1)/2] + 2) > (a[(i-1)/2] + 2) ) {A[i]= (a[(i-1)/2] + 2); C[i]= '-'; } Else{A[i]= (a[(i + 1)/2] + 2); C[i]= ' + '; }            }        }            }    }

Q for a given n, how can you change it to 1 with a minimal number of steps

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.