c++ - 此序列背后的逻辑已构建,但出现问题?
问题描述
我必须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++;
}
解决方案
显然我们只是将所有数字的乘积添加到当前数字。这也适用于 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;
}
即使对于比前十个更多的数字,这也可以正常工作(直到产品或总和发生溢出......)。
推荐阅读
- javascript - JavaScript 对象不会到达 PHP 控制器
- java - 使 Google Maps Android 标记处理多行
- android - 如何在 Android 中使用 MediaRecoder 录制高质量的音频?
- java - 不能在 java 注释中使用 html 标签吗?
- gcloud - Google Cloud ML:重复“尝试刷新以获取初始 access_token”,然后“作业失败”
- powershell - powershell-script 从 EventLog 读取登录和注销
- powershell - 在大文件的尾部之前附加文本
- amazon-s3 - 当我们使用 parition by 创建随机样本时,CTAS 如何在 s3 中创建文件?
- java - 从返回的字符串中删除括号
- visual-studio - Visual Studio 2019 调试 wcf 服务在 Windows 托盘图标中加载 WcfSvcHost.exe 非常慢