首页 > 解决方案 > 此序列背后的逻辑已构建,但出现问题?

问题描述

我必须8将序列的术语打印为

1, 2, 4, 8, 16, 22, 26, 38, ....

我已经完成了我的逻辑,直到16每个新术语都是上一个术语乘以2. 在16逻辑之后,我们将该部分分为两部分

26 = 22 + (2 * 2)

到目前为止我所做的是

int x = 1, num, num1, n = 1;
while (n <= 10)
{
   while (n <= 4)
   {
      if (n == 1)
      {
         cout << x << ", ";
      }
      num = x % 10;
      num1 = num % 10;
      x = x * 2;
      cout << x << ", ";
      n++;
   }
   if (x == 16)
   {
      num = x % 10;
      num1 = num % 10;
      x = x + (num * num1) - 30;
      cout << x << ", ";
   }
   else
   {
      num = x % 10;
      num1 = num % 10;
      x = x + (num * num1);
      cout << x << ", ";
   }
   n++;
}

标签: c++c++14c++17

解决方案


显然我们只是将所有数字的乘积添加到当前数字。这也适用于 1、2、4、8(例如4 = 2 + (2)),因此无需进行任何特殊处理。但是,显然我们需要忽略零,否则我们不会在 102 之后再更改...

所以我们可以稍微简化一下算法:

unsigned int number = 1; // start value
std::cout << number; // OK, would require special handling for n == 0...

while(n--) // you could ask the user to input n or just set it to 10
           // (I consider this variant a bit more elegant)
{
    unsigned int product = 1;
    unsigned int tmp = number;
    // now iterate as long as you have more digits!
    while(tmp)
    {
        unsigned int modulo = tmp % 10;
        tmp /= 10;
        // neat little trick: if modulo != 0, comparison is false, which is
        // converted to 0, which is neutral for OR operation; otherwise, we
        // get 0 | 1, which is neutral for multiplication... 
        product *= modulo | (modulo == 0);
    }
    number += product;
    std::cout << ", " << number;
}

即使对于比前十个更​​多的数字,这也可以正常工作(直到产品或总和发生溢出......)。


推荐阅读