Domanda

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

È stato utile?

Soluzione 2

You must loop using @jubjub's code, until the series hits 0, counting how many times through the loop:

#include <iostream> 
#include <cmath> // pour exp() 
using namespace std; 
int main() 
{ 
    for (int n=0; n<9; ++n)
    { 
        int count = 0, next = n;
        while (next != 0 && count >= 0) 
        {
            if (next % 3 == 0) 
                next += 4;
            else if (next % 4 == 0) 
                next /= 2;
            else 
                next --;
            count ++;
        }
        if (count < 0) 
            cout << "n=" << n << ": could not converge to 0" << endl;
        else
            cout << "n=" << n << ": required " << count << endl;
    }
    return 0;
}

I don't know for this specific series if there is a proof that it will always converge to zero in fewer than some number of steps that depends on n. But I have included a guard in case "count" wraps around to negative numbers.

Altri suggerimenti

Using the modulo operator (%), you can calculate the remainder of a division. This is usually how a program decides if n is divisible by f.

iterations = 0;
while (n != 0) {
    if (n % 3 == 0) n+=4;
    else if (n % 4 == 0) n /=2;
    else n--;
    iterations++
}

I suggest a recursive approach:

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);
}

When you first call num_ops, make sure the prev_ops argument is 0.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top