C++ 中的基思数
在本教程中,我们将编写一个程序来检查给定的数字是否为KeithNumber。
如果数字n出现在使用其数字生成的序列中,则称为基思数。该序列的前n项作为数字n的数字,其他项被递归评估为前n项的总和。
让我们看看解决问题的步骤。
初始化数字n。
初始化一个空向量元素来存储序列。
计算数字并将每个数字添加到向量中。
反转数字向量。
用0初始化一个变量,称为下一个元素。
编写一个循环,迭代直到下一个元素小于n。
添加最后n位数字以获取下一个元素。
将下一个元素添加到向量中。
如果下一个元素等于n则返回true,否则返回false。
示例
让我们看看代码。
#include输出结果using namespace std; bool isKeithNumber(int n) { vector elements; int temp = n, digitsCount = 0; while (temp > 0) { elements.push_back(temp % 10); temp = temp / 10; digitsCount++; } reverse(elements.begin(), elements.end()); int nextElement = 0, i = digitsCount; while (nextElement < n) { nextElement = 0; for (int j = 1; j <= digitsCount; j++) { nextElement += elements[i - j]; } elements.push_back(nextElement); i++; } return nextElement == n; } int main() { isKeithNumber(43) ? cout << "Yes" << endl : cout << "No" << endl; isKeithNumber(14) ? cout << "Yes" << endl : cout << "No" << endl; isKeithNumber(197) ? cout << "Yes" << endl : cout << "No" << endl; return 0; }
如果你运行上面的代码,那么你会得到下面的结果。
No Yes Yes
结论
如果您对本教程有任何疑问,请在评论部分提及。