Lychrel numbers are natural numbers that can never form a palindrome after an iterative process of adding the number to its reverse. The first few numbers that fail to form a palindrome are known as lychrel numbers.
The following code demonstrates how to find lychrel numbers in C++:
#include <iostream>using namespace std;int reverse(int num){int reversed = 0;while(num>0){int mod = num%10;reversed = (reversed*10) + mod;num = num/10;}return reversed;}void isLychrel(int num, int max){//variable that holds 0 if lychrel and 1 if notint lychrel = 0;//duplicate the number for checking laterint num_temp=num;while(num>0){// get the reverseint palindrome = reverse(num);// compare with originalif(palindrome == num){// set the check to 1 and exit looplychrel = 1;break;}// if not a palindrom, reverse the number and add to the original numbernum = reverse(num) + num;// decrease the iteration countmax--;}// display resultsif(lychrel){cout<< "The number "<<num_temp<<" is not lycheral."<<endl;}else{cout<< "The number "<<num_temp<<" is lycheral."<<endl;}}int main() {int max = 10;int num_1 = 35;int num_2 = 295;//check if the number is lychrel or notisLychrel(num_1, max);isLychrel(num_2, max);}
For the sake of implementation, the above code uses a maximum number to limit the iterations. If a palindrome is found within the limit, it is not lychrel.
isLychrel
function, which performs iterations until it finds a palindrome or reaches the maximum limit of iterations.isLychrel
function calls the reverse
function and compares the returned value with the original value to check if the original number is a palindrome or not.reverse
function again, adds the returned value to the original number, and repeats the process.