algorithm - Mathematical and Coding logic to be used for reaching a target number from 0 -


so here's stuck with:

problem: find minimum number of steps required reach target number x 0 (zero), using 2 operations: +1 (add 1 number) or *2 (multiply 2 number).

here's thought/found out:

method 1: suppose number 29, start adding 1 0 (current_ans: 1), keep multiplying 2 current_ans till reach closest value 29, in case becomes 16 (operations: +1 *2 *2 *2 *2). keep adding 1 required number (operations: +1 *2 *2 *2 *2 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1). but, method not give efficient solution total number of steps 18, whereas can done in 8 steps using 2nd method (mentioned below).

here's code snippet same:

int count = 0, current_ans = 0, old_value, x = 29; //x number reach while(current_ans != x) {     old_value = current_ans;     if(current_ans == 0)     {         current_ans++;         count++;     }     if(current_ans < x)     {         current_ans *= 2;         count++;         continue;     }     if(current_ans > x)     {         current_ans = old_value;         count += x - current_ans;         current_ans = x;     } } 

method 2: let take same number 29 , convert binary, 11101. starting 0, take first step +1 (current_ans: 1). next, multiply 2 , convert binary (current_ans: 10). similarly, other operations include +1 (current_ans: 1) *2 (current_ans: 10) +1 (current_ans: 11) *2 (current_ans: 110) +1 (current_ans: 111) *2 (current_ans: 1110) *2 (current_ans: 11100) +1 (current_ans: 11101) , required answer in 8 steps, right answer.

here's code snippet same:

int count = 0, current_ans = 0, old_value, x = 29; //x number reach while(current_ans != x) {     old_value = current_ans;     if(current_ans == 0)     {         current_ans++;         count++;     }     if(current_ans < x) //i not sure of condition     {         current_ans = current_ans << 1;         count++;         continue;     } } 

so, don't know how convert logic working code in c/c++/java/python. if has better solution or code snippet towards solving same helpful. checked out other related questions too, didn't me query. method 2, know can use left shift operation, how use if there's no other better solution?

thanks in advance :)

edit: added code snippets :)

the best way work backwards. start number need:

  1. subtract 1 if number odd.

  2. divide 2 if number if even.

  3. stop when zero.

for example, 29, 28, 14, 7, 6, 3, 2, 1, 0.


c code, intentionally undocumented:

int main() {     int steps = 0;     int x = 29;     (; x; x = x % 2 ? x - 1 : x / 2, ++steps);     return steps; } 

Comments

Popular posts from this blog

Sort a complex associative array in PHP -

vb.net - How to ignore if a cell is empty nothing -

recursion - Can every recursive algorithm be improved with dynamic programming? -