下面是检查给定数字是否为Lychrel数的代码。这基本上意味着该程序取一个数字和它的反向之和,然后取那个数和它的反转等的总和,直到找到回文。如果它在一定的迭代次数内没有找到这样的数字(我在这个程序中选择了50),我们得出结论它是一个Lychrel数。
#include <iostream>
using namespace std;
int rev(int number){ //function to reverse numbers
int rem = 0;
while (number > 0){
rem = (rem * 10) + (number % 10);
number = number / 10;
}
return rem;
}
bool Palindromecheck(int num){ //bool to check if a number is palindrome
return (num == rev(num));
}
bool isLychrel(int checknumber, int &iterationcount){
const int iterCount = 50;
int reversed = rev(checknumber);
int counter = 0;
if (checknumber == reversed){ //makes sure that a number that starts out as a palindrome gets value "0" for iterations
return false;
}
while (counter < iterCount){ //loop that keeps going until it finds a palindrome or reaches 50 iterations
counter = (counter + 1);
iterationcount = counter;
if (Palindromecheck(reversed + checknumber))
return false;
checknumber = checknumber + reversed;
reversed = rev(checknumber);
}
return true;
}
int main()
{
int checknumber;
int iterationcount;
cout << "Please enter a number: \n";
cin >> checknumber;
bool lychrelcheck = isLychrel(checknumber, iterationcount);
if (lychrelcheck == true){
cout << checknumber << " is a Lychrel number. \n";
}
else
cout << checknumber << " is not a Lychrel number. \n";
cout << iterationcount << " is the numbers of iterations necessary to reach a palindrome. \n";
return 0;
}
现在,这个程序在我看到的情况下运行良好,但它有两个我不知道如何解决的错误:
如果你给程序一个1位的数字,它会给你一个非常大的(有时是负数)迭代量。我甚至不知道为什么这应该是可能的,因为最大迭代次数是50.最重要的是,它为相同的数字提供了不同的迭代次数。例如,checknumber = 5可以为您提供巨大的正迭代次数或巨大的负迭代次数。我尝试通过从代码中取一行来稍微修改它来改变它:
bool isLychrel(int checknumber, int &iterationcount){
const int iterCount = 50;
int reversed = rev(checknumber);
int counter = 0;
if ((checknumber == reversed) or (checknumber <= 9)){
}
我认为这会将迭代次数指定为0到10以下的数字,但事实并非如此,由于某种原因,同样的问题仍然存在。
我已经在某个地方读过你可以用include做的事情,但我不知道怎么做。
答案 0 :(得分:1)
对于第一个,如果输入1位数字,则函数会在iterationcount
之前返回任何值。要解决此问题,请在函数开头将iterationcount
设置为0:
int counter = 0;
iterationcount = counter;
实际上,您可以使用iterationcount
作为计数器,而不是为它创建单独的变量。
对于第二个问题,请使用std::numeric_limits<int>::max()
。所以新功能看起来像这样:
bool isLychrel(int checknumber, int &iterationcount) {
const int iterCount = 50;
int reversed = rev(checknumber);
int counter = 0;
iterationcount = counter;
if (checknumber == reversed) { //makes sure that a number that starts out as a palindrome gets value "0" for iterations
return false;
}
while (counter < iterCount) { //loop that keeps going until it finds a palindrome or reaches 50 iterations
if (std::numeric_limits<int>::max() - reversed < checknumber)
return true;
++counter;
iterationcount = counter;
if (Palindromecheck(reversed + checknumber))
return false;
checknumber += reversed;
reversed = rev(checknumber);
}
return true;
}