连续操作与C++

successives operations with C++

本文关键字:C++ 操作 连续      更新时间:2023-10-16

如何执行此代码:

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.

我的问题是我不知道如何连续制作这个。例如:对于数字 6,我必须有:

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

这会产生 10 个操作。

所以我的程序必须返回:6---10

谢谢你的帮助

使用取模运算符 (%),可以计算除法的余数。这通常是程序决定n是否可以被f整除的方式。

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

你必须使用 @jubjub 的代码进行循环,直到序列达到 0,计算循环的次数:

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

我不知道对于这个特定的系列,是否有证据表明它总是在少于依赖于 n 的步数内收敛到零。但是我已经包括了一个警卫,以防"计数"环绕到负数。

我建议采用递归方法:

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。