0

How can I perform this code:

if a number n is divisible by 3, add 4 to n;
if n is not divisible by 3 but by 4, divise n by 2;
if n is not divisible by 3, not by 4, make n=n-1.

The problem with me is that I don't know how to make this successively. For example: with the number 6, I have to have:

6, 10, 9, 13, 12, 16, 8, 4, 2, 1 et 0

6+4=10; 10-1=9; 9+4=13; 13-1=12; 12+4=16; 16/2=8.....0

This makes 10 operations.

So my program has to return: 6---10

Thank you for help

4

3 に答える 3

0

私は再帰的なアプローチを提案します:

int num_ops(int num, int prev_ops) {
  if(num == 0) return prev_ops;

  if((num % 3) == 0)
    return num_ops(num+4, prev_ops+1);

  if((num % 4) == 0)
    return num_ops(num/2, prev_ops+1);

  else
    return num_ops(num-1, prev_ops+1);
}

num_ops を初めて呼び出すときは、prev_ops 引数が 0 であることを確認してください。

于 2013-10-29T12:44:18.377 に答える